gpt4 book ai didi

Java 流 : group a List into a Map of Maps

转载 作者:IT老高 更新时间:2023-10-28 20:50:50 27 4
gpt4 key购买 nike

如何使用 Java Streams 执行以下操作?

假设我有以下类(class):

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 .

我正在努力使用以下两步方法,但第二步甚至无法编译:

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,您可以一次性对数据进行分组:

Map<String, Map<String, Foo>> map = list.stream()
.collect(Collectors.groupingBy(f -> f.b.id,
Collectors.toMap(f -> f.b.date, Function.identity())));

使用静态导入保存一些字符:

Map<String, Map<String, Foo>> map = list.stream()
.collect(groupingBy(f -> f.b.id, toMap(f -> f.b.date, identity())));

关于Java 流 : group a List into a Map of Maps,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33253858/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com