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

Time:06-06

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);
    }

CodePudding user response:

you can try:

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

CodePudding user response:

public static Optional<String> myMethod(final Map myMap) {
        return Optional.ofNullable(myMap == null ? null : (String) myMap.getOrDefault(Constants.SOME_KEY, null));
    }

This should work for you.

  •  Tags:  
  • java
  • Related