这些函数式接口(只有一个abstract方法)都放在java.util.function中
<T> 是泛型的意思
1.Supplier接口
常用的函数式接口 java.util,function.Supplier<T>接口仅包含一个无参的方法:T get().用来获取一个泛型参数指定类型的对象数据 Supplier<T>接口被称之为生产型接口,指定接口的泛型是什么类型,呢么接口中的get方法就会生产什么类型的数据 Supplier方法 <> 泛型中指定什么类型呢就get();就返回什么类型的数据(字符串 Integer)
package Demo19;
import java.util.function.Supplier;
/*
常用的函数式接口
java.util,function.Supplier<T>接口仅包含一个无参的方法:T get().用来获取一个泛型参数指定类型的对象数据
Supplier<T>接口被称之为生产型接口,指定接口的泛型是什么类型,呢么接口中的get方法就会生产什么类型的数据
Supplier方法 <> 泛型中指定什么类型呢就get();就返回什么类型的数据(字符串 Integer)
*/
public class Demo05Supplier {
//定义一个方法,方法的参数传递Supplier<T>接口,泛型执行String.get方法就会返回一个String
public static String getString(Supplier<String> sup){
return sup.get();
}
public static void main(String[] args) {
//调用getString方法,方法的参数Supplier是一个函数式接口所以可以Lambda表达式
String str= getString(()->{
//生产一个字符串并返回
return "tt";//重写的就是Supplier中的get();方法返回到到调用处 注意看是 return sup.get();调用了get方法
});
//优化Lambda
String str02= getString(()->
//生产一个字符串并返回
"tt"//重写的就是Supplier中的get();方法返回到到调用处 注意看是 return sup.get();调用了get方法
);
System.out.println(str);
System.out.println(str02);
}
}
注意这里Lambda重写接口类中的方法这种 其实就是重写了方法 return就看哪里调用了直接给返回去就可以了
2.应用
题目:使用Supplier接口作为方法的参数类型,通过Lambda表达式求出int数组中的最大值。 提示:接口的泛型使用java.lang,Integer类
package Demo19;
import java.util.function.Supplier;
/*
题目:使用Supplier接口作为方法的参数类型,通过Lambda表达式求出int数组中的最大值。
提示:接口的泛型使用java.lang,Integer类
*/
public class SupplierTest {
//既然是函数式接口首先要定义一个方法用于获取int类型数组中元素的最大值,方法的参数传递Supplier,泛型使用Integer
public static int getMax(Supplier<Integer> sup){//注意这里Integer
return sup.get(); //这个就是就是为了返回一个int整数
}
public static void main(String[] args) {
//定义一个int类型的数组
int[] arr = {12,435,656,76,43,-23};
//调用getMax方法,方法的参数Supplier是一个函数式接口所以可以传递Lambda表达式
int maxValue= getMax(()->{ //赋值调用 然后下面重写了Supplier接口中的get();方法
//获取数组的最大值并返回
//定义一个变量,把数组里第一个数赋值给这个变量然后记录数组中元素的最大值
int max =arr[0];
for(int b:arr){
if(max<b){
max =b;
}
}
return max;
});
System.out.println(maxValue);
}
}