函数式接口
概述
格式
函数式接口作为方法的参数的使用
函数式编程
函数式接口作为方法的返回类型的使用
常用函数式接口
1.Supplier–获取数据
eg
练习:获取数组中的最大值
/*idea:求出数组中最大的元素值
* 使用函数式编程,使用supplier接口*/
public class DemoSupplier {
/*定义一个方法将supplier接口作为方法的参数*/
public static Integer getArrayMax(Supplier<Integer> sup){
return sup.get();
}
public static void main(String[] args) {
int[] a={1,3,-8,100,80};
Integer max = getArrayMax(()->{
int m=a[0];
for (int i : a) {
if (m<i) m=i;
}
return m;
});
System.out.println(max);
}
}
2.Consumer接口–(使用)消费数据
eg:
默认方法:andThen
eg:
练习:
3.Predicate接口:对数据进行判断
eg:
默认方法and:与
默认方法or:或
默认方法negate:非(取反)
eg:
Predicate接口练习:集合信息筛选
public class DemoPredicate {
/*定义筛选方法*/
public static ArrayList<String> checkString(String[] arr, Predicate<String> pre1,Predicate<String> pre2){
ArrayList<String> data=new ArrayList<>();
for (String s : arr) {
//两个判断的条件
boolean test = pre1.and(pre2).test(s);
//成立则向集合中添加元素
if(test) data.add(s);
}
return data;
}
public static void main(String[] args) {
String[] s={"迪丽热巴,女","古力娜扎,女","赵丽颖,女","马儿扎哈,男"};
ArrayList<String> d = checkString(s, (String b) -> {
return b.split(",")[1].equals("女");
}, (String b) -> {
return b.split(",")[0].length() == 4;
});
for (String s1 : d) {
System.out.println(s1);
}
}
}
4.Function<T,R>接口:类型转换T–>R
apply方法进行转换
R apply(T t)
将此函数应用于给定的参数
eg:
默认方法andThen:进行组合操作
eg:
/*idea:使用Function<R,T>实现将一个字符串转为Integer+10,然后在转为Integer类型打印输出
* 分析:两次转换操作,可以使用andThen方法
* */
public class FunctionDemo {
/*定义方法实现需求*/
public static void BufferType(String s, Function<String,Integer> f1,Function<Integer,String> f2){
/*Integer i=f1.apply(s);
* String str=f2.apply(i);*/
String str = f1.andThen(f2).apply(s);
System.out.println("转换后的字符串是"+str);
}
public static void main(String[] args) {
String a="125";
BufferType(a,s->Integer.parseInt(s)+10,r->r+"");
}
}