0

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
4
  • What are you trying to sort here? (update: can you describe the goal, and also add more code to reproduce the exception please) Commented Apr 10, 2022 at 19:51
  • Your example code works nice for me - as long as I don't add any map entries with a numeric key and a null value. Commented Apr 10, 2022 at 20:12
  • Where do n and arr come frome? Your update looks weird and doesn't compile, probably you have a typo in if(hm.get(arr[i]!=null)) - right parenthesis in the wrong place? Also your hm.put(arr[i], hm.get(arr[i] + 1); is missing a right parenthesis and now it is not clear, where it should go. Commented Apr 10, 2022 at 20:53
  • I actually could reproduce the problem with some fixes to make it compile (just guessed what might be correct) and this short array: 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 Commented Apr 10, 2022 at 21:07

1 Answer 1

3

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());
Sign up to request clarification or add additional context in comments.

1 Comment

The solution can be extended by constructing and containing two different lists, the first filtering the elements with null fields and no apparent order and the second with the elements that have the comparison fields completed. This way you will have a complete list with the elements with null fields at the beginning or at the end, depending on your content.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.