kumar5
kumar5

Reputation: 188

Converting Nested For Loops To Streams

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.

Upvotes: 2

Views: 1637

Answers (1)

Eran
Eran

Reputation: 393781

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

Upvotes: 10

Related Questions