一,函数式接口介绍
函数式接口的本质还是一个接口,只不过是一种特殊的接口:SAM(Single Abstarct Method)。义了这种类型的接口,使得以其为参数的方法,可以在调用时,使用一个lambda表达式作为参数。从另一个方面说,一旦我们调用某方法,可以传入lambda表达式作为参数,则这个方法的参数类型,必定是一个函数式的接口,这个类型必定会使用@FunctionalInterface进行修饰。
二,简单例子
自定义的一个简单函数式接口:
@FunctionalInterface
public interface MyPredicate<T> {
public boolean test(T t);
}
测试我们写的简单函数式接口:
import java.util.Arrays;
import java.util.List;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Predicate;
public class BiFunctionnalTest {
public static void main(String[] args){
List<Integer> list = Arrays.asList(1,2,3,4,5,6,7,8);
System.out.println(getSum(1,2,(a,b)->a+b));
System.out.println(getSum(1,2,(a,b)->a-b));
System.out.println(getSum(1,2,(a,b)->a*b));
System.out.println("=================================");
//输出所有元素
eval(list, n->true);
//输出偶数
eval(list, n -> n%2 == 0);
evalMy(list, n->true);
evalMy(list, n -> n%2 == 0);
out("come on", n -> System.out.print(n));
}
public static void eval(List<Integer> list, Predicate<Integer> pre){
for(Integer n : list){
if(pre.test(n)){
System.out.println(n+"");
}
}
System.out.println("=================================");
}
public static Integer getSum(Integer a, Integer b, BiFunction<Integer, Integer, Integer> bi){
return bi.apply(a, b);
}
public static void evalMy(List<Integer> list, MyPredicate<Integer> pre){
for(Integer n : list){
if(pre.test(n)){
System.out.println(n+"");
}
}
System.out.println("=================================");
}
public static void out(String input, Consumer<String> test){
test.accept(input);
}
}
输出结果:
3
-1
2
1
2
3
4
5
6
7
8
2
4
6
8
1
2
3
4
5
6
7
8
2
4
6
8
come on
这里写代码片
jdk本身也提供了很多常用的函数式接口,基本都在java.util.function包中了。
参考:https://www.cnblogs.com/ownraul/p/5551545.html
http://www.runoob.com/java/java8-functional-interfaces.html