Alex Georgievskiy Alex Georgievskiy - 1 year ago 65
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]) {
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) {
.filter(n -> -> n == num))

However this method does not test if indexes are the same.

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

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download