I want to find a target sum in an array by adding integers until it's reached, then return the indexes which add up to the target by using streams.
For example, if the provided array is {1, 2, 3, 4} and the target is 4, the method should print out an array of int consisting of indexes {0,2}, but does not.
The code is as below:
public static int[] twoSum(int[] numbers, int target) {
IntStream.of(0, numbers.length - 1).boxed()
.flatMap(i -> IntStream.range(i , numbers.length - 1).boxed()
.filter(j -> numbers[j] + numbers[i] == target)
.flatMap(j -> Stream.of(new int[]{i , j}, new int[] {j,i})))
.forEach(num -> System.out.println(Arrays.toString(num)));
return numbers;
}
public static void main(String[] args) {
System.out.println(Arrays.toString(twoSum(new int[]{1,2,5,1}, 4)));
}