如何从Java IntStream中的嵌套.forEach中收集结果

dja*_*fan 3 java arrays loops java-stream

我正在玩并试图用Java Stream解决这个问题"Two Sum",而不是使用命令式方法:

Given nums = [2, 7, 11, 15], target = 18,
Because nums[1] + nums[2] = 7 + 11 = 18,
return [1, 2].
Run Code Online (Sandbox Code Playgroud)

这是我的部分工作代码.谁能帮忙解决?我只是无法弄清楚如何收集它作为原始int数组返回:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

这是上面的输出(来自窥视):

11
7
Run Code Online (Sandbox Code Playgroud)

deh*_*asi 5

正如我在评论中所说,Streams并不总是一个完美的解决方案.但是关于你的任务,看起来你需要一对Pair.不幸的是,Java没有Tuples(比如Scala),这就是我建议创建一个简单Pair类的原因.

class Pair {
    int i, j;
    public Pair(int i, int j) {
        this.i = i;
        this.j = j;
    }
}
Run Code Online (Sandbox Code Playgroud)

然后,使用一对对

 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());
Run Code Online (Sandbox Code Playgroud)