Efficient way to conditionally add items to HashMap

Manchu Ratt :

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);
Eran :

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));

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=23115&siteId=1