In this Example we are going to understand the exceptions while doing the HashMap methods like compute method.Here we are doing like create or append message to the value for the specific key in the hashmap.
Error Message :
Exception in thread "main" java.lang.NullPointerException
at java.base/java.lang.String.concat(String.java:1946)
at com.si.hashmap.computeHashMap.lambda$0(computeHashMap.java:14)
at java.base/java.util.HashMap.compute(HashMap.java:1228)
at com.si.hashmap.computeHashMap.main(computeHashMap.java:14)
Error Description :
package com.si.hashmap;
import java.util.HashMap;
import java.util.Map;
public class computeHashMap {
public static void main(String[] args) {
Map<String,String> map = new HashMap<String, String>();
map.put("first", "firstValue");
map.put("second", "secondValue");
map.put("third", "thirdValue");
System.out.println(map);
map.compute("first", (key,value)->value.concat(null));
System.out.println(map);
}
}
In the above example ,the red background color line is giving the exception. Here in the Hashmap compute method, in the value part we had concatenate the string ,so we got the Null pointer exception.
Solution:
We need to do the null check for that concat String . If the String is null then do nothing or concat to the hashmap value as in my scenario.
package com.si.hashmap;
import java.util.HashMap;
import java.util.Map;
public class computeHashMap {
public static void main(String[] args) {
Map<String,String> map = new HashMap<String, String>();
map.put("first", "firstValue");
map.put("second", "secondValue");
map.put("third", "thirdValue");
System.out.println(map);
String conVal = "hi";
if(conVal!=null) {
map.compute("first", (key,value)->value.concat(conVal));
}
System.out.println(map);
}
}
Output:
{third=thirdValue, first=firstValue, second=secondValue}
{third=thirdValue, first=firstValuehi, second=secondValue}
With Null value:
{third=thirdValue, first=firstValue, second=secondValue}
{third=thirdValue, first=firstValue, second=secondValue}
Post a comment
Please share your valuable feedback and share this article in social media.