';找不到符号错误';在Java中尝试对数组使用.stream()时
我试图在Java8中实现Java.stream()方法来将一组数字组合在一起。我已经导入了java.util.stream*;包裹静态方法设置为返回int并接受数组。但是,当我在数组上调用.stream().reduce()时,我得到一个错误:';找不到符号错误';在Java中尝试对数组使用.stream()时,java,stream,reduce,Java,Stream,Reduce,我试图在Java8中实现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
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;
}
}
您需要
Arrays.stream
将数组转换为流:
int count = Arrays.stream(x).reduce(1, (a, b) -> a * b);
最后执行的
sum()
步骤没有意义,因为在reduce
之后,我们只剩下一个基本整数。所以我删除了它。首先将数组转换为列表
以流式传输,或者您也可以使用数组。流(x)
作为@Tim Biegeleisen的建议
Arrays.asList(x).stream(x).reduce(1, (a, b) -> a * b);