EdgarHan
EdgarHan

Reputation: 85

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

Upvotes: 3

Views: 139

Answers (1)

ETO
ETO

Reputation: 7289

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())));

Upvotes: 3

Related Questions