brain storm brain storm - 1 year ago 93
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("BAR", getBarType())

In some cases,
would return null. That causes exception to be thrown from
. 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 Source

You can use Optional as the value of the map:

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

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download