Java 8函數編程輕松入門
//定義一個函數接口
@FunctionalInterface
public interface Speak {
void say(String msg);
}
//未新增Lambda表達式的時候,實現Speak接口如下
Speak hello = new Speak() {
@Override
public void say(String msg) {
System.out.println(msg);
}
};
hello.say("hello world.");//輸出hello world.
//新增Lambda表達式之後,實現Speak接口如下,有沒有覺得代碼精簡許多
Speak hello = msg -> System.out.println(msg);
hello.say("hello world.");//輸出hello world.
//lambda表達式版本1
BinaryOperator<Integer> addComplex = (Integer x, Integer y) -> {
return x - y;
};
//利用類型推斷之後的產生版本2,這時候可以省略參數的類型
BinaryOperator<Integer> addComplex = (x, y) -> {
return x - y;
};
//如果Lambda表達式Body只有一行代碼,可以省略掉大括號({})
BinaryOperator<Integer> addComplex = (x, y) -> x - y;
BinaryOperator<Integer> add = (x, y) -> x + y ;
System.out.println(add.apply(1, 2));//3
UnaryOperator<Boolean> result = x -> !x;
System.out.println(result.apply(1 > 0));//false
Predicate<Integer> predicate = x -> x > 0;
System.out.println(predicate.test(1));//true
Consumer<String> say = msg -> System.out.println(msg);
say.accept("Hello World Java 1.8");//Hello World Java 1.8
Function<String, Integer> strLen = m -> m.length();//計算輸入的字符串的長度
System.out.println(strLen.apply("HelloWorld"));//10
Supplier<String> he=()->"HelloWorld.";
System.out.print(he.get());
2.函數接口指僅具有單個抽象方法的接口,用來表示Lambda表達式的類型
1.哪些是Lambda表達式Function<LONG,LONG>的有效實現,並說明不對的理由。
x -> x + 1;
(x, y) -> x + 1;
x -> x ==1;
@FunctionalInterface
public interface Check {
boolean IntPred(Integer n);
}
public class FirstLambda {
public static void main(String[] args) {
Predicate<Integer> predicate = x -> x > 0;
FirstLambda firstLambda = new FirstLambda();
boolean result=firstLambda.check(predicate, 2);
System.out.println(result);
}
public boolean check(Predicate<Integer> predicate, int n) {
return predicate.test(n);
}
public boolean check(Check check, int n) {
return check.IntPred(n);
}
}
更多詳情見請繼續閱讀下一頁的精彩內容: http://www.linuxidc.com/Linux/2016-11/136940p2.htm