Today, Let’s discuss about the Java 8 NullPointerException in Collectors.toMap. The Java 8 Collectors.toMap throws a NullPointerException if one of the values is ‘null’. This error make developers confused and don’t know why this behavior happens, although maps can contain null pointers as value without any problems. Is there a good reason why values cannot be null for Collectors.toMap?
Let’s check the example to see this error happens, we have a java program like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
public class Example { public static void main(String[] args) { List<Answer> answerList = new ArrayList<>(); answerList.add(new Answer(1, true)); answerList.add(new Answer(2, true)); answerList.add(new Answer(3, null)); Map<Integer, Boolean> answerMap = answerList.stream() .collect(Collectors.toMap(Answer::getId, Answer::getAnswer)); } } class Answer { private int id; private Boolean answer; Answer(int id, Boolean answer) { this.id = id; this.answer = answer; } // getter and setter } |
Run the above java program, getting the exception
Actually, this error comes from a Open JDK known bug, but we can work around it with some ways:
Using method putAll() of HashMap:
1 2 |
Map<Integer, Boolean> map = answerList.stream() .collect(HashMap::new, (m,v)->m.put(v.getId(), v.getAnswer()), HashMap::putAll); |
Using forEach:
1 2 |
Map<Integer, Boolean> map= new HashMap<>(); answerList.forEach((answer) -> map.put(answer.getId(), answer.getAnswer())); |
Both of ways, a map will contains null value, like this:
1 2 3 |
key : 1 value : true key : 2 value : true key : 3 value : null |
If you want to filter out null value, using this:
1 2 3 4 5 |
Map<Integer, Boolean> map = answerList .stream() .filter((a) -> a.getAnswer() != null) .collect(Collectors.toMap(Answer::getId, Answer::getAnswer)); |
and the map result don’t contain null value any more:
1 2 |
key : 1 value : true key : 2 value : true |
So depends on your cases and choose the right way. That’s all about the post Java 8 NullPointerException in Collectors.toMap.
You could study more about Java 8 tutorials