Alex Georgievskiy Alex Georgievskiy - 4 months ago 10
Java Question

Get identical values from two int arrays using java 8 features

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

I have a method here 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 with stream is this:

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 test if indexes are the same.

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

edited the code because previous version was giving the indices this one is collecting values to the int array.

Comments