brain storm brain storm - 3 months ago 8
Java Question

elegant way to add non-values to Map in java 8?

I am using immutable map

public Map<String,String> getMap(){
return ImmutableMap.<String,String>builder()
.put("FOO",getFooType())
.put("BAR", getBarType())
.build();
}


In some cases,
getFooType()
or
getBarType()
would return null. That causes exception to be thrown from
com.google.common.collect.ImmutableMap
. I am wondering if there is an elegant way to populate the map only with non-null and non-empty strings.

I am ok with any Map implementation, not confined to guava library.

I could do away with the following

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

String fooType = getFooType();
String barType = getBarType();

if (fooType!=null && fooType.length()>0){
map.put("FOO", fooType);
}

if (barType!=null && barType.length()>0){
map.put("BAR", barType);
}


Since I have many keys to be added to the map, this kind of if-checks make the code not pretty. I am wondering if there is any elegant way to do it.

I am using Java 8 for my project.

Answer

You can use Optional as the value of the map:

public Map<String,Optional<String>> getMap(){
  return ImmutableMap.<String,Optional<String>>builder()
    .put("FOO",Optional.<String>ofNullable(getFooType()))
    .put("BAR", Optional.<String>ofNullable(getBarType()))
    .build();
}

This way the map will store the optional objects wrapping your strings, and when you get values from the map, use map.get(key).orElse(DEF_VALUE); - this will give you the DEF_VALUE for the ones that have null values.

see more here

Comments