Function<T,R>:常用的兩個方法
R apply(T t):將此函式應用于給定的引數
default<V>Function andThen(Function after):回傳一個組合函式,首先將該函式應用于輸入,然后將after函式應用于結果
Function<T,R>介面通常用于對引數進行處理,轉換(處理邏輯由Lambda運算式實作),然后回傳一個新的值
package Demo0513;
?
import java.util.function.Function;
?
public class FunctionDemo {
public static void main(String[] args) {
//呼叫strConvertInt方法
strConvertInt("123",s->Integer.parseInt(s));//Lambda運算式寫法
strConvertInt("456",Integer::parseInt);//方法參考寫法
////呼叫intConcertStr方法
intConcertStr(123,i->String.valueOf(i+566));
//呼叫convert方法
convert("123",s->Integer.parseInt(s),i->String.valueOf(i+566));
?
}
//定義一個方法,把一個字串轉換為int型別,并輸出
private static void strConvertInt(String s, Function<String,Integer>fc){
Integer i = fc.apply(s);
System.out.println(i);
}
//定義一個方法,把一個int型別的資料加上一個整數后轉換為String型別并輸出
private static void intConcertStr(Integer i,Function<Integer,String>fc){
String s = fc.apply(i);
System.out.println(s);
}
//定義一個方法,把一個字串轉換為int型別后加上一個整數轉換為字串,并輸出
private static void convert(String s,Function<String,Integer>fc,Function<Integer,String>fc1){
String ss = fc.andThen(fc1).apply(s);
System.out.println(ss);
}
?
}
練習:
1.創建字串 String s="最美不過姑娘你,18"
2.將此字串的數字年齡資料分割出來,并轉化為int 型別
3.將int 資料加18,得到一個int型別的結果,輸出
4.使用Function介面實作函式拼接
package Demo0513;
import java.util.function.Function;
public class FunctionDemo02 {
public static void main(String[] args) {
//定義字串
//String s="最美不過姑娘你,18";
//呼叫方法
convert("最美不過姑娘你,18",s->Integer.parseInt(s.split(",")[1])+18);
}
//定義方法
private static void convert(String s, Function<String,Integer>fc){
Integer i = fc.apply(s);
System.out.println(i);
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/473463.html
標籤:其他
上一篇:Git常用操作(Gitlab)
