Efficient way to conditionally add items to HashMap

Viewed 823

Is there an efficient and least redundant way to conditionally put new items in map.

GenericObject genericObject;
...
FieldObject obj = genericObject.getFieldObject();
if(obj == null) {
    map.put("key1", null);
    map.put("key2", null);
} else {
    map.put("key1", obj.getField1());
    map.put("key2", obj.getField2());
}

The best I can do is the following, but was curious if there was a better way to do the above in Java 9.

boolean insert = obj != null;
map.put("key1", insert? obj.getField1() : null);
map.put("key2", insert? obj.getField2() : null);
3 Answers

You can use Optionals:

Optional<FieldObject> obj = Optional.ofNullable(genericObject.getFieldObject());
map.put("key1", obj.map(FieldObject::getField1).orElse(null));
map.put("key2", obj.map(FieldObject::getField2).orElse(null));

You could delegate the check for null to the GenericObject by adding these 2 methods to it:

public String getField1() {
    return fieldObject == null ? null : fieldObject.getField1();
}

public String getField2() {
    return fieldObject == null ? null : fieldObject.getField2();
}

Then

map.put("key1", genericObject.getField1());
map.put("key2", genericObject.getField2());

Put null as a value to a map it's quite weird.

map.put("key", null);
map.get("key"); // -- is it null because no such key or because the value is null?

So, is it no necessary to add nulls you just can use optional

Optional.ofNullable(obj).ifPresent(v -> {
   map.put("key1", obj.getField1());
   map.put("key2", obj.getField2());
});

But your plain if-statement is more readable

Related