Function接口
java.util.function.Function<T,R> 接口用來根據一個類型的數據得到另一個類型的數據,前者稱爲前置條件,後者稱爲後置條件。
抽象方法:apply
Function 接口中最主要的抽象方法爲: R apply(T t) ,根據類型T的參數獲取類型R的結果。
使用的場景例如:將String 類型轉換爲Integer 類型
package com.learn.demo07.Function;
import java.util.function.Function;
/*
java.util.function.Function<T,R>接口用來根據一個類型的數據得到另一個類型的數據,
前者稱爲前置條件,後者稱爲後置條件。
Function接口中最主要的抽象方法爲:R apply(T t),根據類型T的參數獲取類型R的結果。
使用的場景例如:將String類型轉換爲Integer類型。
*/
public class Demo01Function {
/*
定義一個方法
方法的參數傳遞一個字符串類型的整數
方法的參數傳遞一個Function接口,泛型使用<String,Integer>
使用Function接口中的方法apply,把字符串類型的整數,轉換爲Integer類型的整數
*/
public static void change(String s, Function<String,Integer> fun){
//Integer in = fun.apply(s);
int in = fun.apply(s);//自動拆箱 Integer->int
System.out.println(in);
}
public static void main(String[] args) {
//定義一個字符串類型的整數
String s = "1234";
//調用change方法,傳遞字符串類型的整數,和Lambda表達式
change(s,(String str)->{
//把字符串類型的整數,轉換爲Integer類型的整數返回
return Integer.parseInt(str);
});
//優化Lambda
change(s,str->Integer.parseInt(str));
}
}