使用流对映射进行排序会抛出“无法调用“java.lang.Comparable.compareTo(Object) 流”

问题描述 投票:0回答:1

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

我想用流对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$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
java hashmap java-stream
1个回答
3
投票

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

List<Integer> temp= hm.entrySet()
                .stream()
                .filter(e -> e.getValue() != null) // <-- added
                .sorted(Entry.comparingByValue())
                .map(Entry::getKey)
                .collect(Collectors.toList());
© www.soinside.com 2019 - 2024. All rights reserved.