使用流 throws"Cannot invoke "java.lang.Comparable.compareTo(Object) stream 对 Map 进行排序”

Sorting an Map using streams throws"Cannot invoke "java.lang.Comparable.compareTo(Object) stream"

我有一个带有整数键和值的 HashMap。我正在尝试按值对这个 hashMap 进行排序,并将这个排序后的映射的键存储在列表中。

我想用stream来对HashMap进行排序。下面是我的代码片段

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());

我该如何解决?

抛出错误:

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$comparingByValue65357e
  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

您的错误表明您在地图中有一个空值,这就是导致错误的原因。因此,要么确保在构建地图时没有空值,要么如下所示将其过滤掉。

List<Integer> temp= hm.entrySet()
                .stream()
                .filter(e -> e.getValue() != null) // <-- added
                .sorted(Entry.comparingByValue())
                .map(Entry::getKey)
                .collect(Collectors.toList());