【问题标题】:"Error: no suitable method found for reduce" when reducing an int[] array减少 int[] 数组时出现“错误:找不到合适的减少方法”
【发布时间】:2021-07-14 02:49:39
【问题描述】:

鉴于这种实现总和的尝试:

int[] nums = { 1,3,4,5,7};
var sum = Arrays.asList(nums).stream().reduce(0,(a,b)->a+b);          

以下问题通常是由于提供给编译器的类型信息不足以进行类型推断。但是这里我们有一个明确的 int[] 数组作为源。为什么会出现这个错误?

Line 3: error: no suitable method found for reduce(int,(a,b)->a + b)
        var sum = Arrays.asList(nums).stream().reduce(0,(a,b)->a+b);
                                              ^
    method Stream.reduce(int[],BinaryOperator<int[]>) is not applicable
      (argument mismatch; int cannot be converted to int[])
    method Stream.<U>reduce(U,BiFunction<U,? super int[],U>,BinaryOperator<U>) is not applicable
      (cannot infer type-variable(s) U
        (actual and formal argument lists differ in length))
  where U,T are type-variables:
    U extends Object declared in method <U>reduce(U,BiFunction<U,? super T,U>,BinaryOperator<U>)
    T extends Object declared in interface Stream

【问题讨论】:

    标签: java stream reduce


    【解决方案1】:

    var sum = Arrays.asList(nums) 返回一个 List,因此 reduce 方法将 int[] 添加到 int[],这是不允许的,会导致编译错误。

    这是一个可能的解决方案:

        int[] nums = { 1,3,4,5,7};
        var sum= Arrays.stream(nums).reduce(0,(a,b)->a + b);
    

    var result = Arrays.stream(nums).sum();
    
    
    
         
    

    【讨论】:

    • 啊,不错。这是一个很快就被接受的答案 - 恭喜!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-07-30
    • 1970-01-01
    • 2018-10-13
    • 1970-01-01
    • 1970-01-01
    • 2010-12-17
    • 1970-01-01
    相关资源
    最近更新 更多