问题
I'm having some trouble understanding streams. I've looked around and can't seem to find an example that matches my use case.
I have an existing nested for loop:
List<ObjectB> objectBs = new ArrayList<ObjectB>();
for (ObjectA objA: objectAList) {
for (ObjectB objB: objA.getObjectBList()) {
if (objB.getNumber() != 2) {
objectBs.add(objB);
}
}
}
Alot of exampls show how to add objB.getNumber()
to a list but not objB
.
回答1:
You can use flatMap
to obtain a Stream<ObjectB>
of all the ObjectB
instances and filter the ObjectB
's of the required number :
List<ObjectB> objectBs =
objectAList.stream()
.flatMap (a -> a.getObjectBList().stream())
.filter (b -> b.getNumber() != 2)
.collect (Collectors.toList());
来源:https://stackoverflow.com/questions/36744975/converting-nested-for-loops-to-streams