Javier León
Javier León

Reputation: 33

List from List Streams JAVA8

I need go through a list(class A) from lists(classB). I want to use streams JAVA8, but go through the second list i lose the reference from first list

class A {
   Collection<B> listB ;
   String x;
   // Some other variables
}

class B {
   String y;
   // Some other variables
}

// List object A

Collection<class A> listA;

listA.stream()
    .filter(a -> a.getListaB() != null)
    .flatMap(a -> a.getListB().stream())
    .forEach(b -> {
                // Here lose reference object A
                // I need something like a.getX()
                // I need too use something like b.getY(), use both lists
                    });

The error is "cannot find simbol variable a" I understand the error, There is any solutions use streams and not foreach or for loop?

Upvotes: 3

Views: 84

Answers (1)

davidxxx
davidxxx

Reputation: 131496

Because you don't nest the second stream to the first one but you flatten it :

.flatMap(a -> a.getListB().stream())

So finally after this statement you get simply a stream<B> of all elements of Lists of B.

To solve you requirement, nest the stream and use forEach() instead of flatMap() as here you don't want to transform anything but you want to apply a Consumer :

Collection<A> listA = ...;

listA.stream()
    .filter(a -> a.getListaB() != null)
    .forEach(a -> a.getListB().stream()
               .forEach(b -> {
                    // a and b are usable now
                })
       );

Upvotes: 3

Related Questions