Java Streams: group a List into a Map of Maps(Java Streams:将列表分组为地图的地图)
问题描述
如何使用 Java Streams 执行以下操作?
How could I do the following with Java Streams?
假设我有以下课程:
class Foo {
Bar b;
}
class Bar {
String id;
String date;
}
我有一个 List<Foo>
并且我想将它转换为 Map <Foo.b.id, Map<Foo.b.date, Foo>
.即:首先按 Foo.b.id
分组,然后按 Foo.b.date
.
I have a List<Foo>
and I want to convert it to a Map <Foo.b.id, Map<Foo.b.date, Foo>
. I.e: group first by the Foo.b.id
and then by Foo.b.date
.
我正在努力使用以下两步方法,但第二步甚至无法编译:
I'm struggling with the following 2-step approach, but the second one doesn't even compile:
Map<String, List<Foo>> groupById =
myList
.stream()
.collect(
Collectors.groupingBy(
foo -> foo.getBar().getId()
)
);
Map<String, Map<String, Foo>> output = groupById.entrySet()
.stream()
.map(
entry -> entry.getKey(),
entry -> entry.getValue()
.stream()
.collect(
Collectors.groupingBy(
bar -> bar.getDate()
)
)
);
提前致谢.
推荐答案
假设只有不同的 Foo
,您可以一次性对数据进行分组:
You can group your data in one go assuming there are only distinct Foo
:
Map<String, Map<String, Foo>> map = list.stream()
.collect(Collectors.groupingBy(f -> f.b.id,
Collectors.toMap(f -> f.b.date, Function.identity())));
使用静态导入保存一些字符:
Saving some characters by using static imports:
Map<String, Map<String, Foo>> map = list.stream()
.collect(groupingBy(f -> f.b.id, toMap(f -> f.b.date, identity())));
这篇关于Java Streams:将列表分组为地图的地图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Java Streams:将列表分组为地图的地图


基础教程推荐
- Java 实例变量在两个语句中声明和初始化 2022-01-01
- 在 Java 中创建日期的正确方法是什么? 2022-01-01
- 从 python 访问 JVM 2022-01-01
- 如何在 JFrame 中覆盖 windowsClosing 事件 2022-01-01
- 大摇大摆的枚举 2022-01-01
- 验证是否调用了所有 getter 方法 2022-01-01
- 不推荐使用 Api 注释的描述 2022-01-01
- 如何在 Spring @Value 注解中正确指定默认值? 2022-01-01
- 多个组件的复杂布局 2022-01-01
- Java Swing计时器未清除 2022-01-01