Java 8 extract non null and non empty value from HashMap

ppb :

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?

smac89 :

Not sure why you check if the map is null, 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.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=432861&siteId=1