问题
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());
回答1:
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());
回答2:
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
来源:https://stackoverflow.com/questions/56014710/java-8-collecting-the-list-that-is-already-present-in-object