尝试在Java中的数组上使用.stream()时出现“找不到符号错误”

时间:2018-09-21 03:20:37

标签: java stream reduce

我正在尝试在Java 8中实现Java.stream()方法以将多个数字列表在一起。我已经导入了java.util.stream *;。包。静态方法设置为返回一个int并接受一个数组。但是,当我在数组上调用.stream()。reduce()时,出现错误:

error: cannot find symbol
    int count = x.stream().reduce(1, (a, b) -> a * b).sum();
                 ^
  symbol:   method stream()
  location: variable x of type int[]

如何正确使用stream()方法将数组中的值按顺序排列在一起?

我定义为的类:

import java.util.stream.*;
public class Kata{
  public static int grow(int[] x){
    int count = x.stream().reduce(1, (a, b) -> a * b).sum();
    return count;  
  }

}

2 个答案:

答案 0 :(得分:4)

您需要Arrays.stream才能将数组转换为流:

int count = Arrays.stream(x).reduce(1, (a, b) -> a * b);

最后执行的sum()步骤没有意义,因为在reduce之后,我们只剩下一个原始整数。所以我删除了它。

答案 1 :(得分:1)

首先将数组转换为List进行流传输,或者也可以将Arrays.stream(x)用作@Tim Biegeleisen建议

Arrays.asList(x).stream(x).reduce(1, (a, b) -> a * b);