【问题标题】:Two List merge with java 8两个 List 与 java 8 合并
【发布时间】:2021-06-08 04:09:05
【问题描述】:

有两个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 ...}]},
]

【问题讨论】:

  • 到目前为止你尝试了什么?请显示一些代码。
  • @EdgarHan 不要将代码 sn-ps 放入 cmets,而是将它们附加到问题
  • @Nikolai Shevchenko 谢谢你,我编辑了我的帖子
  • @EdgarHan 可能也会添加预期的输出。

标签: java lambda collections java-8 java-stream


【解决方案1】:

试试这个:

Map<Integer, B> bMap = bList.stream()
                            .collect(toMap(B::getId, identity()));

aList.forEach(a -> a.setBList(a.getBIds()
                               .stream()
                               .map(bMap::get)
                               .collect(toList())));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-03-02
    • 2018-05-10
    • 1970-01-01
    • 2019-04-17
    • 2018-06-05
    • 1970-01-01
    • 2013-08-20
    相关资源
    最近更新 更多