Saving / reusing intermediate results in java 8 thread

I have a list A, In order to filter, I need to map A to B. But as soon as the filtering logic is done, I still need A for further operations. So my question is, can this be achieved at all? One approach that I can come up with is to store both A and B in the third type, so I have both options when processing a stream, but I'm not sure if this is elegant and interesting if the best way is here. Or I'm trying a square pin in a round hole using threads.

List<A> a; List<B> b = a.stream().map(i -> load(i)).filter(need A here in addition to b) 
+7
java java-8 java-stream
source share
3 answers

Well, you can always pass two things enclosed in Pair , array , List , for example:

 a.stream().map(i -> List.of(load(i), i)) // List#of is java-9, replace with Pair or array .filter(x -> x[0]...) .filter(y -> /* y is List here */) 
+3
source share

There is no elegant solution here, but you can do filtering inside the display:

 .map(a -> { B b = load(a); return filter(a, b) ? b : null; }) .filter(Objects::nonNull) 

You do not need to create wrappers around flow elements. The load method will only execute once if it is an expensive operation.

null is an invalid default value, it should be replaced if null enabled or it can be returned from load .

+1
source share

You can use the anonymous class on the fly (or any suitable existing class to represent a pair or similar):

 a.stream().map(e -> new Object() { A a=e; B b=load(e); }) .filter(x -> /*any code using xa and xb */) 

Keep in mind that some IDEs do not accept this as long as it is perfect Java 8 code.

0
source share

All Articles