In java 8 lambdas, how to access the source object in a stream?

Say I have a list of 'A'

List<A> as; 

If I want to do a fair processing bit for each A and at the end of processing, I want to take the result and put it in another field A, what is the best way to do this?

t

 as.stream(). map(a -> a.getX()). filter(x -> x != null). map(x -> lookup.get(x)). At this point how to say y -> a.setLookedUpVal(y)? 

I lost the link to "a" further in the lambda chain. Is there any way to save it and return to it or something else?

+6
source share
2 answers

If you have a more complex scenario or don’t like @Aaron's answer for any reason, you can perform a flat matrix trick that creates a stream of one element for each outer element:

 as.stream(). flatMap(a -> Stream.of(a.getX()). filter(x -> x != null). map(x -> a)). forEach(System.out::println); 

Here we have a nested stream for each element, where you can perform any stateless operations ( map , filter , peek and flatMap ) that have a link to the source element. After the source element becomes unnecessary, you close flatMap and continue the source stream. Example:

 Stream.of("a", "bb", "ccc", "dd", "eeee") .flatMap(a -> Stream.of(a.length()) .filter(x -> x > 2) .map(x -> a)) .forEach(System.out::println); // prints "ccc" and "eeee". 

Or two filters:

 Stream.of("a", "bb", "ccc", "dd", "eeee") .flatMap(a -> Stream.of(a.length()) .filter(x -> x > 2) .map(x -> a.charAt(0)) // forget the length, now check the first symbol .filter(ch -> ch == 'c') .map(x -> a)) // forget the first symbol, reverting to the whole string .forEach(System.out::println); // prints only "ccc" 

Of course, such simple scripts can be rewritten as @Aaron suggests, but in more complex cases, flatMap-capture might be the solution.

+5
source

I do not know if you can access unmodified elements, but you can redo your chain of operations as follows:

 as.stream() .filter(a -> a.getX() != null) .forEach(a -> a.setLookedUpVal(lookup.get(a.getX())) 

Now I understand that this makes it more complicated and may not be interesting in solving your real problem.
However, the advantage is that they all work together with Stream<A> , which in some situations can be simpler and more extensible than different types at different stages.

+4
source

All Articles