I have two integer arrays e.g. -
int[] a = {2, 7, 9}
int[] b = {4, 2, 8}
I want to compare it element by element i.e. 2 to 4 then 7 to 2 and finally 9 to 8. Each comparison result will be stored in a list.
This is pretty easy to do in the traditional Java ways. But I want to use Stream here. Any pointers?
You're essentially looking for the functionality of a Zip operation (which is not available in Java yet).
To get a set of booleans, as a result, I would recommend:
boolean[] accumulator = new boolean[a.length];
IntStream.range(0, a.length)
         .forEachOrdered(i -> accumulator[i] = a[i] == b[i]);
and respectively to get the result as an int between corresponding elements in both arrays:
int[] ints = IntStream.range(0, a.length)
                      .map(i -> Integer.compare(a[i], b[i]))
                      .toArray();
                        You may do it like so,
List<Boolean> equalityResult = IntStream.range(0, a.length).mapToObj(i -> a[i] == b[i])
                .collect(Collectors.toList());
Precondition: both the arrays are of same size.
Assuming the length of both the input arrays are same
List<Integer> list = IntStream.range(0, a.length).mapToObj(i -> Integer.compare(a[i], b[i]))
            .collect(Collectors.toCollection(() -> new ArrayList<>(a.length)));
                        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