s-day07- 常用的函数式接口_Supplier
This commit is contained in:
@@ -0,0 +1,28 @@
|
||||
package com.inmind.functional_supplier04;
|
||||
|
||||
import java.util.function.Supplier;
|
||||
|
||||
/*
|
||||
JDK为了避免各个程序员定义一些重复的无效的函数式接口,所以,它就提供了一些常用的函数式接口
|
||||
Supplier<T> :表示生产者
|
||||
T:泛型,用来决定生产者要生产数据类型
|
||||
|
||||
Supplier<T> 提供了一个生产方法:T get() 获得结果。
|
||||
|
||||
总结:Supplier<T>的作用,当我们想要定义一个无参有返回值的函数式接口时,就使用Supplier
|
||||
|
||||
举例:想要定义一个无参有返回值(String)的函数式接口:Supplier<String> -->String get()
|
||||
举例:想要定义一个无参有返回值(Student)的函数式接口:Supplier<Student> -->Student get()
|
||||
*/
|
||||
public class Demo07 {
|
||||
public static void main(String[] args) {
|
||||
method(()->"这是结果");//省略写法
|
||||
method(()->{return "这是结果";});//完整写法
|
||||
method(()->100);//省略写法
|
||||
}
|
||||
|
||||
public static void method(Supplier supplier) {
|
||||
Object o = supplier.get();
|
||||
System.out.println(o);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package com.inmind.functional_supplier04;
|
||||
|
||||
import java.util.function.Supplier;
|
||||
|
||||
/*
|
||||
使用Supplier求数组的最大值(我需要一个生产者,它要生产出一个最大值,如何实现由lambda表达式去实现)
|
||||
*/
|
||||
public class Demo08 {
|
||||
public static void main(String[] args) {
|
||||
int[] arr = {10,20,30,40,50};
|
||||
getMax(()->{
|
||||
int max = arr[0];
|
||||
for (int temp : arr) {
|
||||
if (temp > max) {
|
||||
max = temp;
|
||||
}
|
||||
};
|
||||
return max;
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
public static void getMax(Supplier<Integer> supplier){
|
||||
Integer max = supplier.get();
|
||||
System.out.println("生产者中的最大值为:"+max);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user