Reputation: 109
I have a HashMap with an Integer key and value. I am trying to sort this hashMap by values and store the keys of this sorted map in a list.
I want to use stream to sort HashMap. Below is my code snippet
Map<Integer, Integer> hm
= new HashMap<Integer, Integer>();
int arr[]=new int[]{1,2,2,3,3,3,4,4,5};
n-arr.length;
for (int i = 0; i < n; i++) {
if(hm.get(arr[i])!=null)
hm.put(arr[i], hm.get(arr[i]) + 1);
else
hm.put(arr[i],1);
List<Integer> temp= hm.entrySet()
.stream()
.sorted(Map.Entry.comparingByValue())
.map(entry -> entry.getKey())
.collect(Collectors.toList());
How can I fix it?
The error is thrown:
java.lang.NullPointerException: Cannot invoke "java.lang.Comparable.compareTo(Object)" because the return value of "java.util.Map$Entry.getValue()" is null
at line 541, java.base/java.util.Map$Entry.lambda$comparingByValue$1065357e$1
at line 355, java.base/java.util.TimSort.countRunAndMakeAscending
at line 220, java.base/java.util.TimSort.sort
at line 1307, java.base/java.util.Arrays.sort
at line 353, java.base/java.util.stream.SortedOps$SizedRefSortingSink.end
at line 510, java.base/java.util.stream.AbstractPipeline.copyInto
at line 499, java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto
at line 921, java.base/java.util.stream.ReduceOps$ReduceOp.evaluateSequential
at line 234, java.base/java.util.stream.AbstractPipeline.evaluate
at line 682, java.base/java.util.stream.ReferencePipeline.collect
at line 16, Solution.topKFrequent
at line 54, __DriverSolution__.__helper__
at line 87, __Driver__.main
Upvotes: 0
Views: 3690
Reputation: 40034
Your error says you have a null value in the map so that is what is causing the error. So either ensure there are no nulls when the map is constructed or filter them out as shown below.
List<Integer> temp= hm.entrySet()
.stream()
.filter(e -> e.getValue() != null) // <-- added
.sorted(Entry.comparingByValue())
.map(Entry::getKey)
.collect(Collectors.toList());
Upvotes: 3