案例1
import java.util.function.Supplier;
/**
* 常用的函數式接口
* java.util.function.Supplier<T>:接口中僅包含一個無參的方法:T get();用來獲取一個指定泛型參數的對象數據
* Supplier<T>接口被稱爲是一個生產型接口,指定接口的泛型是什麼類型,那麼接口中get方法獲取的就是什麼類型的數據
*
*/
public class SupplierDemo {
public static String getString(Supplier<String> sup){
return sup.get();
}
public static void main(String[] args) {
String str = getString(()-> "AA" );
System.out.println(str);
}
}
案例2
import java.util.function.Supplier;
/**
* 常用的函數式接口
* java.util.function.Supplier<T>:接口中僅包含一個無參的方法:T get();用來獲取一個指定泛型參數的對象數據
* Supplier<T>接口被稱爲是一個生產型接口,指定接口的泛型是什麼類型,那麼接口中get方法獲取的就是什麼類型的數據
*
*/
public class SupplierDemo {
public static int getMax(int[] arr,Supplier<Integer> sup){
return sup.get();
}
public static void main(String[] args) {
int[] arrs = {1,2,34,1,23};
int result = getMax(arrs,()->{
int max=arrs[0];
for (int i = 1; i < arrs.length; i++) {
if(arrs[i]>max)
max = arrs[i];
}
return max;
});
System.out.println(result);
}
}