Java Streams:将列表分组为地图的地图

2022-01-22 00:00:00 java-8 java java-stream

如何使用 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())));

相关文章