有两个 List 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流做到这一点?
不工作此代码
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 ...}]},
]
试试这个:
Map<Integer, B> bMap = bList.stream()
.collect(toMap(B::getId, identity()));
aList.forEach(a -> a.setBList(a.getBIds()
.stream()
.map(bMap::get)
.collect(toList())));
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句