Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 extract non null and non empty value from HashMap

Let consider a below HashMap

HashMap<String, String> map = new HashMap<String, String>();

I have values in map like

map.put("model", "test");

Currently, if I want to get value from map I am doing

if(map!=null){
 if(map.get("model")!=null && !map.get("model").isEmpty()){
   //some logic
 }
}

Is there any better approach in Java 8 by using Optional or Lambdas to achieve the above condition?

like image 418
ppb Avatar asked Nov 08 '17 22:11

ppb


2 Answers

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.

like image 33
smac89 Avatar answered Oct 05 '22 13:10

smac89


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.

like image 172
JB Nizet Avatar answered Oct 05 '22 12:10

JB Nizet