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?
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.
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.
Yes, null is always a valid map key for any type of map key (including primitives, sobjects, and user-defined objects).
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".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With