Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check null value of map

Tags:

java

I am getting map as result and when I am getting value I need to convert it to String like below:

a.setA(map.get("A").toString());

but if it returns null than it throws nullPointerException, so I change it with below:

a.setA(map.get("A")!=null?map.get("A").toString():"");

but there are more than 20 fields for that I am doing the same so I just want to do like below:

String val = "";
a.setA(val=map.get("A")!=null?val.toString():"");

but it returns blank all time, I have just simple question is can't I use variable like this? or is there any other option for doing the same?

like image 925
commit Avatar asked Aug 22 '13 11:08

commit


People also ask

How do you check null value on a map?

util. HashMap. isEmpty() method of HashMap class is used to check for the emptiness of the map. The method returns True if no key-value pair or mapping is present in the map else False.

How do I tell if a map key is null?

To make sure key exists you should use HashMap#containsKey(key) function. Once key exists you may use HashMap#get(key) to get the value and compare it to null.

Can a map value be null?

Yes, null is always a valid map key for any type of map key (including primitives, sobjects, and user-defined objects).


1 Answers

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".

like image 193
JB Nizet Avatar answered Oct 16 '22 10:10

JB Nizet