有两个列表vo类
class A {
Integer aid;
List<Integer> bIds;
List<B> bList;
}
class B {
Integer id;
String Name;
}
List<A> aList; //size:3, bIds: {2,3}, {1,2}, {3}
List<B> bList; //id [{bId:1, ...},{bId:2, ...},{bId:3, ...},{bId:4, ...},{bId:5, ...}]
我想将B对象放入每个A对象的列表中。
如何使用Java Stream实现这一目标?
以下代码无效。
aList.forEach(
a -> {
a.setBList(
a.getBIds().stream()
.flatMap(id -> b.stream().filter(b -> b.getId() == id))
.collect(Collectors.toList())
);
}
);
期望的输出结果
//pre
aList = [
{aid: 1, bIds: [2,3], bList:[]},
{aid: 2, bIds: [1,2], bList:[]},
{aid: 3, bIds: [3], bList:[]},
]
//after
aList = [
{aid: 1, bIds: [2,3], bList:[{bId:2 ...},{bId:3 ...}]},
{aid: 2, bIds: [1,2], bList:[{bId:1 ...},{bId:2 ...}]},
{aid: 3, bIds: [3], bList:[{bId:2 ...}]},
]