在Java 8中按值对Hashmap进行排序

Bry*_*ryn 2 java java-8

我有一个HashMap,我需要按值排序,我试图保持简洁,所以我使用Java 8.但是各种方法都不起作用,我不确定为什么.我试过这个:

followLikeCount.values()
  .stream()
  .sorted(Map.Entry.comparingByValue())
  .collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)

这会抛出这个编译时异常:

Main.java:65: error: no suitable method found for sorted(Comparator<Entry<Object,V#1>>)
  .sorted(Map.Entry.comparingByValue())
Run Code Online (Sandbox Code Playgroud)

我不明白为什么观察不匹配.我也尝试过使用比较器:

Comparator<Map.Entry<Integer, Integer>> byValue =
          Map.Entry.<Integer, Integer>comparingByValue();
Run Code Online (Sandbox Code Playgroud)

这会产生类似的错误.请问您能告知为什么比较器无效?

azr*_*zro 5

您尝试使用Comparator<Map.Entry<Integer, Integer>>on List<Integer>返回values()

followLikeCount.values()
   .stream()
   .sorted(Map.Entry.comparingByValue())
   .collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)

你需要使用这个比较器Set<Map.Entry<Integer, Integer>>,可以通过以下方式返回entrySet():

List<Map.Entry<Integer, Integer>> list = followLikeCount.entrySet()
                                                    .stream()
                                                    .sorted(Map.Entry.comparingByValue())
                                                    .collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)

如果您只想获取值,已排序,您可以更改Comparator并返回List<Integer>:

List<Integer> list = followLikeCount.values()
            .stream()
            .sorted(Comparator.naturalOrder())
            .collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)