Reputation: 43
I was just searching for better way to handle this scenario using java 8 streams. Object A has list of object b. What I get is a list of object A (List). I need to stream through list of object A and get all the listB's in each of the object A as a one single list.
class A {
List<B> listB
}
I have tried the below way it throws compilation
List<A> as = someObject.getAs();
List<B> listofBs = as.stream().map(in -> in.getListB()).collect(Collectors.toList());
Upvotes: 1
Views: 326
Reputation: 380
Class A{
List<B> listB
};
List<A> listA;
listA.stream().map(
a->{
//some code for A
a.ListB.stream().map(
b->{
// some code for B
})
});
may be help you
Upvotes: 0
Reputation: 31968
To get a single list of all B's, you should use flatMap
as:
List<B> listOfBs = listOfAs.stream()
.flatMap(a -> a.getListB().stream())
.collect(Collectors.toList());
Upvotes: 4