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.