Java 8 extract non null and non empty value from HashMap
First of all, your Map should not be null. Never. It could be empty, but there's no reason for it to be null. So that eliminates the first null check.
Now, unfortunately, Java doesn't have such a utility method, but several commonly used libs (apache commons, Guava, etc.) have it, or you can write it yourself, so it becomes:
String model = map.get("model");
if (!Strings.isEmptyOrNull(model)) {
// do somthing
}
Using Optional to wrap a nullable value as part of your logic is considered an antipattern. Optional is designed to be used as a return type. So I wouldn't advide using it here.
Also note that it feels like you're using a map to store attributes of an object If it is so, then consider defining a real class, with typed properties, instead of using a map.
Not sure why you check if the map is null after just having created it, but here goes:
Optional.ofNullable(map)
.map(m -> m.getOrDefault("model", "")) // Use an empty String if not present
.filter(s -> !s.isEmpty()) // Filter all empty values
.ifPresent(valueString -> { // Check if value is present
// Logic here
});
Or in one line:
Optional.ofNullable(map).map(m -> m.getOrDefault("model", "")).filter(s -> !s.isEmpty()).ifPresent(valueString -> {
// Logic here
});
Change ifPresent
to map
if you want to return something; i.e. Optional of whatever you calculate.
If you are interested in an Optional
approach,
You can wrap a map.get("model")
value into an Optional.ofNullable
and do filter work by the Predicate<String>
value -> !value.isEmpty()
:
if (isNull(map)) { // import static java.util.Objects.isNull;
return; // to minimise nesting
}
Optional.ofNullable(map.get("model"))
.filter(value -> !value.isEmpty())
.ifPresent(value -> { ... });