2014-10-09 725 views
0

試圖測試Java8拉姆達,但類型是混亂:Java8功能類型`(A,B) - >一個+ B`

import java.util.function.ToIntBiFunction; 
import java.util.stream.IntStream; 

public class Test { 
    public static void main(String... args) { 

    int sum1 = 0; 
    for (int n = 0; n < 10; n++) { 
     sum1 += n; 
     } 


    ToIntBiFunction<Integer, Integer> add = (a, b) -> a + b; 
    int sum2 = IntStream.range(0, 10) 
         .reduce(0, add); //error here 


    System.out.println(""+sum1); 
    System.out.println(""+sum2); 

    } 
} 

Test.java:15:錯誤:不兼容的類型:ToIntBiFunction無法轉換爲IntBinaryOperator .reduce(0,add);

什麼來定義函數

(a,b) -> a+b

由於最通用的方法。

回答

4

最通用的方式是一個lambda,一旦你把它分配給一個變量,或將其轉換爲一個類型就成爲一個特定的類型。

嘗試類型的減少()預計

IntBinaryOperator add = (a,b) -> a+b 

或者使用內置的一個。

int sum2 = IntStream.range(0, 10) 
        .reduce(0, Integer::sum); 
+0

我喜歡內置的'Integer :: sum',非常感謝Peter! – 2014-10-09 08:10:24

1

顯然,您需要IntBinaryOperator代替.reduce(),而不是ToIntBiFunction

IntBinaryOperator add = (a, b) -> a + b; 
int sum2 = IntStream.range(0, 10) 
        .reduce(0, add); 
+0

謝謝kocko! – 2014-10-09 08:10:52

相關問題