Simplify code: return a value from map if map is not null and contains key

Viewed 80

Can the following piece of code be simplified?

    public Optional<String> myMethod(final Map myMap) {

        String result = null;
        if (myMap != null && myMap.containsKey(Constants.SOME_KEY)) {

            result = (String) myMap.get(Constants.SOME_KEY);
        }
        return Optional.ofNullable(result);
    }
1 Answers

you can try:

public Optional<String> myMethod(final Map<String, String> myMap) {
        return Optional.ofNullable(myMap != null ? myMap.getOrDefault("Key", null) : null);
    }
Related