Get identical values ​​from two int arrays using java 8 functions

Is it possible to compare two integer arrays using the stream API and return an array containing elements that are the same in both arrays and have the same index (provided that the two arrays have the same length).

I have a method not using java 8:

public static int[] identicalValueAndIndex(int[] array1, int[] array2) {
    List<Integer> values = new ArrayList<Integer>();
    int len = array1.length;
    for (int i = 0, k = 0; i < len; i++) {
        if (array1[i] == array2[i]) {
            values.add(array1[i]);
        }
    }
    int[] result = new int[values.size()];
    for (int i = 0; i < values.size(); i++) {
        result[i] = values.get(i);
    }
    return result;
}

The closest I got the stream:

public static int[] identicalValueAndIndex(int[] array1, int[] array2) {
    return Arrays.stream(array1)
            .filter(n -> Arrays.stream(array2).anyMatch(num -> n == num))
            .toArray();
}

However, this method does not check if the indices match.

+4
source share
1 answer

  Elements are identical in both arrays and have the same index (provided that the two arrays have the same length)

This code can do the job as required:

int[] values = IntStream.range(0, array1.length)
    .filter(i - > array1[i] == array2[i])
    .map(i - > array1[i])
    .toArray();
+6

Source: https://habr.com/ru/post/1649612/


All Articles