如何根据其值的参数对Map进行排序? [英] How can I sort a Map according to the parameters of its values?

查看:147
本文介绍了如何根据其值的参数对Map进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Stream<Map.Entry<String, List<Object>>> sorted = index.entrySet().stream()
                .sorted(Map.Entry.comparingByValue());




方法已排序(Comparator<?super Map.Entry< String,List< NFArticle>>>),类型为 Stream< Map.Entry< String,List< NFArticle>>> 不适用于
参数(比较器< Map.Entry< Object,Comparable<?super Comparable<?super V>>>>)

我想根据<我要对 Hashmap 进行排序code> size()列表是 HashMap 的值。如何使用Java 8中的Stream库实现这一目标?

I want to sort a Hashmap according to the size() of Lists being the values of the HashMap. How can I achieve this using the Stream library from Java 8?

推荐答案

这可能会对您有所帮助。

This may be helpful to you.

我将结果地图的类型更改为 LinkedHashMap 以尊重广告订单。

I changed the type of result map to LinkedHashMap to respect insertion order.

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));
}

这篇关于如何根据其值的参数对Map进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆