简体   繁体   中英

Compare two integer arrays using Java Stream

I have two integer arrays eg -

int[] a = {2, 7, 9}

int[] b = {4, 2, 8}

I want to compare it element by element ie 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 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)));

Same as other answers with a bit difference

List<Integer> result = IntStream.rangeClosed(0,a.length-1)
            .boxed()
            .map(i->Integer.compare(a[i],b[i]))
            .collect(Collectors.toList());

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM