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.