Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two List merge with java 8

There is two List vo class

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

I wanna put B object in a list in each A object

how to get I do this with java stream?

not working this code

        aList.forEach(
                a -> {
                    a.setBList(
                            a.getBIds().stream()
                                .flatMap(id -> b.stream().filter(b -> b.getId() == id))
                                .collect(Collectors.toList())
                    );
                }
        );

expect out put

//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 ...}]},
]
like image 208
EdgarHan Avatar asked Mar 13 '26 22:03

EdgarHan


1 Answers

Try this:

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

aList.forEach(a -> a.setBList(a.getBIds()
                               .stream()
                               .map(bMap::get)
                               .collect(toList())));
like image 108
ETO Avatar answered Mar 16 '26 12:03

ETO



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!