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?
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.
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.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With