如何根据其值的参数对Map进行排序?
Stream<Map.Entry<String, List>> sorted = index.entrySet().stream() .sorted(Map.Entry.comparingByValue());
在
Stream<Map.Entry<String,List>>
类型中sorted(Comparator<? super Map.Entry<String,List>>)
的方法sorted(Comparator<? super Map.Entry<String,List>>)
不适用于参数(Comparator <Map.Entry<Object,Comparable<? super Comparable>>>)
我想根据Lists的值( HashMap
的值size()
对Hashmap
进行排序。 如何使用Java 8中的Stream库实现此目的?
这可能对您有所帮助。
我将结果映射的类型更改为LinkedHashMap以尊重插入顺序。
public static void main(String[] args) { final Map> 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 Map> getMapSortedByListSize(final Map> 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)); }
Map.Entry.comparingByValue()
仅在地图中的值为Comparable
且List
不可Comparable
时才有效。 编译器的错误告诉你。
您需要提供一个自定义Comparator
,它知道如何按大小对列表进行排序,例如
Map.Entry.comparingByValue((list1, list2) -> list1.size() - list2.size())
Map.Entry.comparingByValue()
不能作为比较器。
这是Stream
:
Stream>> sortedStream = index.entrySet().stream() .sorted(new Comparator>>() { @Override public int compare(Entry> o1, Entry> o2) { return o1.getValue().size()-o2.getValue().size(); } });