Check null value of map

Use a method. And avoid calling get() twice:

private String valueToStringOrEmpty(Map<String, ?> map, String key) {
    Object value = map.get(key);
    return value == null ? "" : value.toString();
}

...

String a = valueToStringOrEmpty(map, "A");
String b = valueToStringOrEmpty(map, "B");

Now repeat after me: "I shall not duplicate code".


with Java 8 you can do the following:

a.setA(map.getOrDefault("A", "").toString());

Why don't you create a util method to this like:

public String getMapValue(Map m, String a){

    String s = m.get(a);
    if(s == null)
        return "";
    else
        return s;
}

Now you just need to call this method:

String val = getMapValue(map,"A");
a.setA(val);

Tags:

Java