我如何像Lambda一样使用Lambda在Java中将List的值分组 [英] How can I group values of List in Java using Lambda like we do in python

查看:482
本文介绍了我如何像Lambda一样使用Lambda在Java中将List的值分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想根据键对地图的值进行分组.假设

I want to group values of a map based on the key. Let's say

Map<String,Integer> map1 = new TreeMap<String,Integer>();
map1.put("D", 3);
map1.put("B", 2);
map1.put("C", 1);

Map<String,Integer> map2 = new TreeMap<String,Integer>();
map2.put("A", 13);
map2.put("B", 22);
map2.put("C", 12);

Map<String,Integer> map3 = new TreeMap<String,Integer>();
map3.put("A", 33);
map3.put("B", 32);
map3.put("C", 32);

Map<Integer,Map<String,Integer>> map = new HashMap <Integer,Map<String,Integer>>();

map.put(1,map1);
map.put( 2, map2);
map.put(3, map3);
System.out.println(map);

我想根据键对映射中的值进行分组:输出应为["A","B","C"]:[2,3], ["D","B","C"]:[1]

I want to group values in the map based on the keys: Output should be ["A","B","C"]:[2,3], ["D","B","C"]:[1]

所以我做了什么:

Map<List<String>, List<Integer>> newMap = new HashMap<List<String>, List<Integer>>();

for (Integer item : map) {
    Map<String,Integer> currentValue = map.get(item);
    List<String> oldItemKeySet = newMap.get(currentValue.keySet());
    newMap.put(currentValue.keySet(), (oldItemKeySet == null) ? 1 : oldItemKeySet.put());
}

但是它无法解决问题,任何人都可以在这里提供帮助.

But it doesn't work out, can anyone help here.

PS:在Python中,这些事情可以用itertools.groupbyreduce完成,但是我仍然不知道如何在Java中完美地做到这一点

PS: In Python, these things can be done with itertools.groupby or reduce, but i am still don't knoww how to do it perfectly in Java

推荐答案

如果我很了解,您希望将与在与原始键相关联的最后一个地图中添加的地图的相同键集进行分组.

If I understand well, you want to group the identical key set of the maps you added in the last map associated with the original key.

import static java.util.stream.Collectors.groupingBy;
import static java.util.stream.Collectors.mapping;
import static java.util.stream.Collectors.toList;

...

Map<Set<String>, List<Integer>> newMap = 
    map.entrySet()
       .stream()
       .collect(groupingBy(e -> e.getValue().keySet(), 
                           mapping(Map.Entry::getKey, toList())));

从最后一个映射中,您获得条目流(这是一个Stream<Entry<Integer, Map<String, Integer>>).在那里,您可以根据地图值的键集对条目进行分组.

From the last map, you get the stream of entries (which is a Stream<Entry<Integer, Map<String, Integer>>). There you group the entries by the key set of their map's values.

然后,您使用下游收集器映射结果映射的值,该收集器收集List<Integer>中原始条目的键.

Then you map the values of the resulting map using a downstream collector, which collects the keys of the original entries in a List<Integer>.

输出:

{[A, B, C]=[2, 3], [B, C, D]=[1]}

这篇关于我如何像Lambda一样使用Lambda在Java中将List的值分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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