Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare two integer arrays using Java Stream

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?

like image 345
Saikat Avatar asked Oct 13 '18 04:10

Saikat


3 Answers

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();
like image 104
Ousmane D. Avatar answered Oct 22 '22 04:10

Ousmane D.


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.

like image 39
Ravindra Ranwala Avatar answered Oct 22 '22 05:10

Ravindra Ranwala


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)));
like image 29
Naman Avatar answered Oct 22 '22 03:10

Naman