函数式接口:有且仅有一个抽象方法的接口
eg:
@FunctionalInterface
public interface MyInterface {
void show();
}
一、常用函数式接口
1、Supplier
java.util.function.Supplier?接口仅包含一个无参的方法: T get() 。用来获取一个泛型参数指定类型的对象数据。由于这是一个函数式接口,这也就意味着对应的Lambda表达式需要“对外提供”一个符合泛型类型的对象数据。eg:
public class SupplierDemo {
public static void main(String[] args) {
/* String s = getString(()->"林青霞");
System.out.println(s);*/
/* Integer in = getInteger(()->98);
System.out.println(in);*/
int[] arr = {19,12,15,67,89,43,66};
int maxvalue = getMax(()->{
int max = arr[0];
for(int i = 0; i<arr.length;i++){
if(arr[i]>max){
max = arr[i];
}
}
return max;
});
System.out.println(maxvalue);
}
private static Integer getMax(Supplier<Integer> sup){
return sup.get();
}
private static Integer getInteger(Supplier<Integer> sup){
return sup.get();
}
private static String getString(Supplier<String> sup){
return sup.get();
}
}
2、Consumer
java.util.function.Consumer?接口则正好与Supplier接口相反,它不是生产一个数据,而是消费一个数据, 其数据类型由泛型决定。eg:
import java.util.function.Consumer;
public class ConsumerDemo2 {
public static void main(String[] args) {
String[] array = {"甄嬛,17", "沈眉庄,18", "华妃,20", "安陵容,17"};
operatorString(array, s -> {
String name = s.split(",")[0];
System.out.print("姓名:" + name);
}, s -> {
int age = Integer.parseInt(s.split(",")[1]);
System.out.println(",年龄:" + age);
});
}
private static void operatorString(String[] array, Consumer<String> con1, Consumer<String> con2) {
for (String s : array) {
con1.andThen(con2).accept(s);
}
}
}
3、Predicate
Predicate 接口中包含一个抽象方法: boolean test(T t) 。用于条件判断的场景,得到一个boolean值结果。eg:
import java.util.ArrayList;
import java.util.function.Predicate;
public class PredicateDemo2 {
public static void main(String[] args) {
String[] strarray = {"甄嬛,17", "沈眉庄,18", "华妃,20", "安陵容,17"};
ArrayList<String> result = myFilter(strarray, s -> s.split(",")[0].length() < 3, s -> Integer.parseInt(s.split(",")[1]) < 18);
System.out.println(result);
}
private static ArrayList<String> myFilter(String[] strarr, Predicate<String> pre1, Predicate<String> pre2){
ArrayList<String> array = new ArrayList<>();
for(String s: strarr){
if(pre1.and(pre2).test(s)){
array.add("姓名:"+s.split(",")[0]+" 年龄:"+s.split(",")[1]);
}
}
return array;
}
}
4、Function
java.util.function.Function<T,R> 接口用来根据一个类型的数据得到另一个类型的数据,前者称为前置条件,后者称为后置条件。eg:
import java.util.function.Function;
public class FunctionDemo2 {
public static void main(String[] args) {
String name = "甄嬛,17";
ageAdd(name, s -> s.split(",")[1], s -> Integer.parseInt(s), i -> i + 10);
}
private static void ageAdd(String s, Function<String, String> fun1, Function<String, Integer> fun2, Function<Integer, Integer> fun3) {
int i = fun1.andThen(fun2).andThen(fun3).apply(s);
System.out.println("十年后的年龄是:" + i);
}
}
|