I wrote a tiny example to explain my problem:
import java.util.Arrays;
import java.util.List;
public class Example {
public static void main( String[] args ) {
String [] array = {"1 0101 5","1 0101 5"};
Arrays.stream(array)
.map(str->str.split(" "))//every String is mapped to an array of String
.map(arr-> returnAListOf5Element( Integer.parseInt(arr[0]),arr[1],Integer.parseInt(arr[2])))
.forEach(list-> tesMyList(list));//i want to send the Integer.parseInt(arr[2]) as a second argument
}
/**
*
* test if the list has size of 5
*/
private static void testMyList(List<Integer> myList) {
if (myList.size()==5)
System.out.println("Ok");
}
/**
*
* return a list of 5 element
* @return
*/
private static List<Integer> returnAListOf5Element( int i, String s, int i1 ) {
List list = Arrays.asList(1,2,3,4,5);
return list;
}
}
So I have some Strings like "1 0101 5","1 0101 5"....., i use stream operation to make some calcul.
The problem is i want to add the argument arr[2] found in the map method to the testMyList method found in the foreach method.
the method testMyList should be like:
private static void testMyList(List<Integer> myList, int size) {
if (myList.size()==size)
System.out.println("Ok");
}
I can see three possible solutions:
returnAListOf5Element
returnsarr[2]
within the list. (let's say, by contact, it's the last element in the returned list.) It's a dirty approach.map
returns aMap.Entry<List<Integer>, Integer>
which is composed of the result of thereturnAListOf5Element(...)
call andarr[2]
. It's a more reasonable way.
These two ides are based on caching state of a previous operation so you can get it at a next one. It's the only way to obtain the result calculated in the chain before.
- You replace the stream chain with a simple loop where each intermediate calculation is accessible.
I find the last method the most simple and performance-wise. It doesn't seem that you are going to reap any benefits from streams here. I would stick to it.