转换地图< K,V>映射< V,列表< K>> [英] Converting Map<K, V> to Map<V,List<K>>

查看:87
本文介绍了转换地图< K,V>映射< V,列表< K>>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的地图如下所示

Map<String, String> values = new HashMap<String, String>();
values.put("aa", "20");
values.put("bb", "30");
values.put("cc", "20");
values.put("dd", "45");
values.put("ee", "35");
values.put("ff", "35");
values.put("gg", "20");

我想以 Map< String,List<格式创建新地图字符串>> ,示例输出将为

"20" -> ["aa","cc","gg"]
"30" -> ["bb"]
"35" -> ["ee","ff"]     
"45" -> ["dd"]

我可以通过迭代实体来完成

I am able to do by iterating through entity

Map<String, List<String>> output = new HashMap<String,List<String>>();
    for(Map.Entry<String, String> entry : values.entrySet()) {
        if(output.containsKey(entry.getValue())){
            output.get(entry.getValue()).add(entry.getKey());

        }else{
            List<String> list = new ArrayList<String>();
            list.add(entry.getKey());
            output.put(entry.getValue(),list);
          }
    }

使用流可以做得更好吗?

Can this be done better using streams?

推荐答案

groupingBy 可用于按值对键进行分组。如果在没有映射 收集器的情况下使用,它将转换 Stream 地图条目( Stream< Map.Entry< String,String>> )到 Map< String,List< Map.Entry< String ,String>> ,这很接近你想要的,但不完全。

groupingBy can be used to group the keys by the values. If used without a mapping Collector, it will transform a Stream of map entries (Stream<Map.Entry<String,String>>) to a Map<String,List<Map.Entry<String,String>>, which is close to what you want, but not quite.

为了使输出 Map 的值为 List 的原始密钥,你必须将映射 收集器链接到 groupingBy 收藏家

In order for the value of the output Map to be a List of the original keys, you have to chain a mapping Collector to the groupingBy Collector.

Map<String,List<String>> output =
    values.entrySet()
          .stream()
          .collect(Collectors.groupingBy(Map.Entry::getValue,
                                         Collectors.mapping(Map.Entry::getKey,
                                                            Collectors.toList())));
System.out.println (output);

输出:

{45=[dd], 35=[ee, ff], 30=[bb], 20=[aa, cc, gg]}

这篇关于转换地图&lt; K,V&gt;映射&lt; V,列表&lt; K&gt;&gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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