I am playing around and trying to solve this problem "Two Sum" with a Java Stream, not using the imperative method:
Given nums = [2, 7, 11, 15], target = 18,
Because nums[1] + nums[2] = 7 + 11 = 18,
return [1, 2].
And here is my partially working code. Can anyone help solve? I just can't figure out how to collect it back up to be returned as a primitive int array :
class Solution {
public int[] twoSum(int[] input, int target) {
IntStream.range(0, input.length)
.forEach(i -> {
IntStream.range(0, input.length)
.filter(j -> i != j && input[i] + input[j] == target)
.peek(t -> System.out.println(input[t]))
.findFirst();
}
);
return null;
}
}
And here is the output of the above (coming from peek):
11
7
As I said in comments Streams are not always a perfect solution. But regarding your task, it looks like you need a stream of Pair. Unfortunately Java does not have Tuples (like Scala) that's why I suggest to create a simple Pair class.
class Pair {
int i, j;
public Pair(int i, int j) {
this.i = i;
this.j = j;
}
}
Then, work with a stream of pairs
IntStream.range(0, input.length)
.boxed()
.flatMap(i -> IntStream.range(0, input.length).boxed()
.map(j -> new Pair(i,j))
)
.filter(p -> p.i != p.j)
.filter(p -> input[p.i] + input[p.j] == target)
.collect(toList());
The common recipe to mimic nested for loops that drive a list or an array via indexes is to use IntStream along with flatMap:
int[] input = {12, 7, 11, 15, 6, 2};
int target = 18;
List<List<Integer>> result = IntStream.range(0, input.length)
.boxed()
.flatMap(i -> IntStream.range(i + 1, input.length)
.filter(j -> input[i] + input[j] == target)
.mapToObj(j -> Arrays.asList(i, j)))
.collect(Collectors.toList());
System.out.println(result); // [[0, 4], [1, 2]]
Note that you don't need a Pair class to maintain state from the inner stream to the outer stream, because you can apply the needed filter to the inner stream.
Besides, the inner IntStream is not required to start on 0, because you don't want to have both [i, j] and [j, i] in the result (only one of them is needed). So starting the inner IntStream with i + 1 is enough.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With