java - 如何像在 python 中那样使用 Lambda 对 Java 中的 List 值进行分组

标签 java python lambda

我想根据键对映射的值进行分组。让我们说

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]

所以我做了什么:

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

但是没有成功,有人可以帮忙吗?

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

最佳答案

如果我理解得很好,您希望将在与原始键关联的最后一个映射中添加的映射的相同键集进行分组。

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

从最后一张 map 中,您可以获得条目流(即 Stream<Entry<Integer, Map<String, Integer>> )。在那里,您可以根据映射值的键集对条目进行分组。

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

输出:

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

关于java - 如何像在 python 中那样使用 Lambda 对 Java 中的 List 值进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33900057/

相关文章:

java模块访问问题: "Class in a module cannot access class in unnamed module because module x does not read unnamed module y"

python - Pandas:从数据帧返回行,其中多个列子集不为零

java - 此有效的 Java 代码从 javac 1.8 update 91 产生错误

c++ - "Error: expected a ' { ' introducing a lambda body"尝试从 map<char,char> C++ 获取 char

java - 编写一个程序,提示用户输入两点(包括工作)

java - 如何正确地将TextureRegion映射到Pixmap?

java - 将 boolean 数组作为字段添加到 Firestore 文档

python - 如何让 Pandas 打印出数据而不是内存地址?

python - 在数据框中应用单元函数

c# - 转换 Lambda 表达式参数类型