Find a pair of integers from an array that sums up to a given number in Java 8 using functionals

arrays, functional-programming, java, java-8

Solution

You can make them final. If nothing else, you can write

for (int i = 0; i < arr.length; i++) {
    final int[] arrFinal = arr;
    final int iFinal = i;
    List<Integer> res = IntStream.of(arr).boxed()
        .filter(x -> x + arrFinal[iFinal] == givenNumber)
        .collect(Collectors.toList());
}

though I'd write it as

for (int i = 0; i < arr.length; i++) {
    int target = givenNumber - arr[i];
    List<Integer> res = IntStream.of(arr).filter(x -> x == target)
                           .boxed().collect(Collectors.toList());
}

...which also makes it clear, for what it's worth, that you're just going to have a list of a single value repeated some number of times, which might reshape your program in the first place.

Problem

I was looking at the problem of finding a pair of two integers from an array that sums up to a given number in Java in a different way. I wanted to use Java 8 functionals. I tried something like this: ``` for (int i = 0; i < arr.length; i++) { List<Integer> res = IntStream.of(arr).boxed().filter(x -> x + arr[i] == givenNumber) .collect(Collectors.toList()); } ``` but it won't work(error) because "arr[i]" is not final and can't be final in my approach. Can something like: filter(x -> y -> x + y == givenNumber) with x and y from arr work somehow? So could this be done in Java 8 using functional programming? If the answer is yes, then how?

Original source