Stream<Map.Entry<String, List<Object>>> sorted = index.entrySet().stream()
.sorted(Map.Entry.comparingByValue());
The method sorted(Comparator<? super Map.Entry<String,List<NFArticle>>>)
in the type Stream<Map.Entry<String,List<NFArticle>>>
is not applicable for the
arguments (Comparator <Map.Entry<Object,Comparable<? super Comparable<? super V>>>>)
我想对 Hashmap
进行排序根据size()
列表的值是 HashMap
的值.如何使用 Java 8 中的 Stream 库实现此目的?
这可能对你有帮助。
我将结果映射的类型更改为 LinkedHashMap 以遵守插入顺序。
public static void main(String[] args) {
final Map<String, List<Integer>> map = new HashMap<>();
map.put("k1", Arrays.asList(new Integer[]{1, 2, 3, 4, 5}));
map.put("k2", Arrays.asList(new Integer[]{1, 2, 3, 4, 5, 6}));
map.put("k3", Arrays.asList(new Integer[]{1, 2, 3}));
System.out.println(getMapSortedByListSize(map));
}
public static <K, V> Map<K, List<V>> getMapSortedByListSize(final Map<K, List<V>> map) {
return map.entrySet().stream()
.sorted((e1, e2) -> e1.getValue().size() - e2.getValue().size())
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (a, b) -> a, LinkedHashMap::new));
}