Java Streams:将List分组为Map的Map

19 浏览
0 Comments

Java Streams:将List分组为Map的Map

请问如何使用Java Streams来实现以下操作?

假设我有以下类:

class Foo {
    Bar b;
}
class Bar {
    String id;
    String date;
}

我有一个 `List`,我想将其转换为 `Map `。即先按 `Foo.b.id` 分组,然后再按 `Foo.b.date` 分组。

我正在尝试以下两步骤的方法,但第二步甚至无法编译:

Map> groupById =
        myList
                .stream()
                .collect(
                        Collectors.groupingBy(
                                foo -> foo.getBar().getId()
                        )
                );
Map> output = groupById.entrySet()
        .stream()
        .map(
                entry -> entry.getKey(),
                entry -> entry.getValue()
                        .stream()
                        .collect(
                                Collectors.groupingBy(
                                        bar -> bar.getDate()
                                )
                        )
        );

提前感谢您的帮助。

0