【发布时间】:2020-04-26 11:26:34
【问题描述】:
假设有 3 个类:
class Level1 {
int idLevel1;
List<Level2> level2list;
}
class Level2 {
int idLevel2;
List<Level3> level3list;
}
class Level3 {
int idLevel3;
String name;
}
假设有一个称为初始状态的 Level1 对象列表
List<Level1> initialList = new ArrayList<>();
我想从 initialList 创建一个地图,其中:
- Key: is idLevel1
- Value: is list of all idLevel3 , corresponding to idLevel1
我可以使用 for 循环来实现这一点,但我想使用 Java 8 特性(流和函数)以更优雅的方式实现这一点。 我尝试使用 Collectors.toMap() 也尝试过分组,但我无法获得所需的地图。
【问题讨论】:
-
一串两个
flatMap,好像。 -
向我们展示您的尝试 - 除了给出答案之外,我们还可以根据您的尝试帮助您:)
-
Elegant不一定表示best。 -
不应该
Level2类定义中的level2List真的是level3List吗? -
@WJS 是的,你是对的,应该是
level3List
标签: java collections java-8 functional-programming java-stream