如何根据值List的大小对java中的HashMap进行排序 [英] How to sort HashMap in java depending on the size of value List

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

问题描述

我有一个类似以下的散列图

I have a hashmap like the following

HashMap<String, ArrayList<String>> map=new HashMap<String, ArrayList<String>>();

map.put("USA", Arrays.asList("CA","IA","IL"));
map.put("India", Arrays.asList("MUM","CAL"));
map.put("Canada", Arrays.asList("TOR"));

我想根据值中列表的大小按升序对地图进行排序。如何我能做到吗有没有很好的方法呢?

I want to sort the map depending on the size of the list in the value in ascending order.How can i do that. Is there any nice method to do so?

推荐答案

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

您可以替换 comparisonInt(e-> e.getValue()。 size()) with comparisonByValue(comparisonInt(List :: size))如果你发现更可读

You can replace comparingInt(e->e.getValue().size()) with comparingByValue(comparingInt(List::size)) if you find that more readable

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

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