函数式编程–函数式接口(前提需要会使用lambda表达式!!!!!!)
函数式接口的使用简单来说就是把方法体作为参数传递给方法使用!
好处就是很灵活,想怎么使用就怎么使用,复用性很强。(个人感觉)
提问:什么是函数式接口?
有且只有一个抽象方法的接口被称之为函数式接口,函数式接口只适用于函数式编程场景。
条件一:它是一个接口
条件二:有且只有一个抽象方法
函数式接口主要有Consumer(消费型)、Supplier(提供型)、Predicate(断言型)、Function(方法型)。
统一的使用步骤:
1.定义函数接口。
2.给函数式接口赋值(方法体)。
3.调用其抽象方法(本质是在调用你赋的值(方法体))。
4.使用结束,有的有返回值有的没有返回值。
Consumer(消费型)
public interface Consumer<T> {
void accept(T t);
}
消费型接口就是有参数无返回值(这里有可能不理解消费是什么意思,使用参数即消费!),只需要向这个接口提供参数拱其使用即可。
使用:
//(可以把函数式接口的值理解为方法体!)
//示例一 创建一个消费型接口consumer给它赋值
Consumer<Integer> consumer = a -> System.out.println(a);
consumer.accept(3);//输出3
//示例二 将函数式接口作为方法的形参,方法体作为实参传递给方法
print(a -> System.out.println(a));//输出3
public void print(Consumer<Integer> consumer){
return;
}
Supplier(提供型)
@FunctionalInterface
public interface Supplier<T> {
T get();
}
提供型接口就是无参数有返回值(这里和java bean中的get方法作用差不多)。
使用:
//(可以把函数式接口的值理解为方法体!)
//示例一 创建一个消费型接口supplier 给它赋值
Supplier<Integer> supplier = () -> new Integer(5);
System.out.println(supplier.get());//结果为5
//示例二 将函数式接口作为方法的形参,方法体作为实参传递给方法
get(() -> new Integer(5));//返回值为5
public Integer get(Supplier<Integer> supplier){
return supplier.get();
}
Predicate(断言型)
@FunctionalInterface
public interface Predicate<T> {
boolean test(T t);
}
断言型接口是是一个判断接口,返回true或者false
使用:
//(可以把函数式接口的值理解为方法体!)
//示例一 创建一个断言型接口predicate 给它赋值
Predicate<Integer> predicate = i -> i<0;
predicate.test(1);//返回false
predicate.test(-1);//返回true
//示例二 将函数式接口作为方法的形参,方法体作为实参传递给方法
test(i -> i<0,1);//返回false
test(i -> i<0,-1);//返回true
public Boolean test(Predicate<Integer> predicate,Integer t){
return predicate.test(t);
}
Function(方法型)
@FunctionalInterface
public interface Function<T, R> {
R apply(T t);
}
方法型接口就是有参数有返回值,需要向这个接口提供参数(泛型T)并接收返回值(泛型R)。
使用:
//(可以把函数式接口的值理解为方法体!)
//示例一 创建一个方法型接口function 给它赋值
Function<Integer,Integer> function = a -> a+1;
System.out.println(function.apply(2));//输出3
//示例二 将函数式接口作为方法的形参,方法体作为实参传递给方法
Integer result = add(a -> a+1,2);
System.out.println(result);//输出3
public Integer add(Function<Integer,Integer> function,Integer i){
return function.apply(i);
}
其他类型
其他的类型都是在上述基本四种类型的基础上增强的,看看源码就懂了。