4

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.

1 Answer 1

6

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

This code can do the job according to requirements:

int[] values = IntStream.range(0, array1.length)
    .filter(i - > array1[i] == array2[i])
    .map(i - > array1[i])
    .toArray();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.