Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I access the value of a previous lambda in a stream chain?

I have this stream code, which does not compile:

itemList.stream()
    .map(im -> item2dogsMap.get(im.getEan()))
    .flatMap(List<Dog>::stream)
    .forEach(d -> System.out.println("item" + im + " with dog " + d));

The problem is that in the forEach statement I need im and d. But it cannot resolve im here.

I could create an ItemAndDog class taking the two values and do a new in the map statement. But that looks like overkill to me. Is there a way to do this without creating an extra class?

like image 908
BetaRide Avatar asked Dec 09 '15 11:12

BetaRide


People also ask

Is it possible to modify source of stream of lambda expression in stream operation?

This is possible only if we can prevent interference with the data source during the execution of a stream pipeline. And the reason is : Modifying a stream's data source during execution of a stream pipeline can cause exceptions, incorrect answers, or nonconformant behavior.

Can you reuse a stream Java?

No. Java streams, once consumed, can not be reused by default. As Java docs say clearly, “A stream should be operated on (invoking an intermediate or terminal stream operation) only once.


2 Answers

You can not. If you convert your lambdas to anonimous inner classes, you will see, the variables which you wanted to use are out of scope.

like image 114
Sándor Juhos Avatar answered Sep 21 '22 00:09

Sándor Juhos


You can solve the problem creating the resulting string inside the flatMap where you will have an access to both variables like this:

itemList.stream()
    .flatMap(im -> item2dogsMap.get(im.getEan()).stream()
        .map(d -> "item" + im + " with dog " + d))
    .forEach(System.out::println);
like image 25
Tagir Valeev Avatar answered Sep 21 '22 00:09

Tagir Valeev