Java Streams:将List分组到Maps地图中 [英] Java Streams: group a List into a Map of Maps
本文介绍了Java Streams:将List分组到Maps地图中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我如何使用Java Streams执行以下操作?
How could I do the following with Java Streams?
假设我有以下类:
class Foo {
Bar b;
}
class Bar {
String id;
String date;
}
我有列表< 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:将List分组到Maps地图中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文