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
nullvalue.nandarrcome frome? Your update looks weird and doesn't compile, probably you have a typo inif(hm.get(arr[i]!=null))- right parenthesis in the wrong place? Also yourhm.put(arr[i], hm.get(arr[i] + 1);is missing a right parenthesis and now it is not clear, where it should go.Integer[] arr = new Integer[] {2,1,2};If you can confirm that this causes the problem for you as well (and maybe fix your code), I can post an answer