如何根据值List的大小对java中的HashMap进行排序

Md *_*lam 9 java sorting java-8 java-stream

我有一个像下面这样的hashmap

Map<String, List<String>> map = new HashMap<>();

map.put("USA", Arrays.asList("CA","IA","IL"));
map.put("India", Arrays.asList("MUM","CAL"));
map.put("Canada", Arrays.asList("TOR"));
Run Code Online (Sandbox Code Playgroud)

我想根据值中升序排列的列表大小对地图进行排序.我该怎么做.有没有很好的方法呢?

Mis*_*sha 17

import static java.util.Comparator.comparingInt;
import static java.util.stream.Collectors.toMap;

Map<String, List<String>> sorted = map.entrySet().stream()
    .sorted(comparingInt(e -> e.getValue().size()))
    .collect(toMap(
        Map.Entry::getKey,
        Map.Entry::getValue,
        (a, b) -> { throw new AssertionError(); },
        LinkedHashMap::new
    )); 
Run Code Online (Sandbox Code Playgroud)

您可以替换HashMap使用LinkedHashMap,如果你发现更易读

  • 第一个代码很有效。后者则不然。另外,如果您想要尺寸降序使用......................................`(e -&gt; `comparingInt` 中的 -e.getValue().size())`。您可以看到后者不在这里:https://code.sololearn.com/ccz02MbYMYs1/#java [给出 2 个编译错误:1) 找不到用于 ComparisonByValue 的符号 2) 参数不匹配;无效方法参考] (2认同)