I'm trying to figure out how to use the Streams API to implement a zip function that takes an unbounded number of int[]'s as an argument; takes the i'th element from each; puts those in a Tuple (obviously a custom Tuple object is needed - which I have) and returns a list of Tuples (i.e. List).
Essentially, for:
{ 1, 2, 3 }
{ 4, 5, 6 }
the proposed method should return:
[ Tuple(1, 4), Tuple(2, 5), Tuple(3, 6) ]
as a java.util.List<Tuple>
Here is a function that does what I'm trying to do in a "normal" way:
/**
* Return a list of tuples, where each tuple contains the i-th element
* from each of the argument sequences. The returned list is
* truncated in length to the length of the shortest argument sequence.
*
* @param args the array of ints to be wrapped in {@link Tuple}s
* @return a list of tuples
*/
public static List<Tuple> zip(int[]... args) {
List<Tuple> retVal = new ArrayList<>();
// Find the array with the minimum size
int minLength = Arrays.stream(args).map(i -> new Integer(i.length)).min((a, b) -> a.compareTo(b)).get();
for(int i = 0;i < minLength;i++) {
Tuple.Builder builder = Tuple.builder();
for(int[] ia : args) {
builder.add(ia[i]);
}
retVal.add(builder.build());
}
return retVal;
}