1.函数式接口(Functional Interface):—->函数式接口可以被隐式转换为lambda表达式
函数式接口, 首先是一个接口,在这个接口里面只能有一个抽象方法。也称为SAM接口
1.1函数式接口里允许定义默认
1.2 函数式接口里允许定义静态
1.3 函数式接口里允许定义java.lang.Object里的public
1.4 函数式接口里允许子接口继承多个父接口,但每个父接口中都只能存在一个抽象方法,且必须的相同的抽象方法
注意:
函数式接口中可以额外定义多个抽象方法,但这些抽象方法签名必须和Object的public方法一样 如:Comparator
JDK 1.8之前已有的函数式接口:
java.lang.Runnable
java.util.concurrent.Callable
java.security.PrivilegedAction
java.util.Comparator
java.io.FileFilter
java.nio.file.PathMatcher
java.lang.reflect.InvocationHandler
java.beans.PropertyChangeListener
java.awt.event.ActionListener
javax.swing.event.ChangeListener
JDK 1.8 新增加的函数接口:
java.util.function
java.util.function 它包含了很多类,用来支持 Java的 函数式编程,在这里只讲
Predicate<T> :接受一个输入参数,返回一个布尔值结果。
2、实例说明
public class FunctionInter {
public static void main(String[] args) {
int [] testStr = {1, 2, 3, 4, 5, 6, 7, 8, 9};
List<Integer> list = new ArrayList<Integer>();
for (Integer integer : testStr) {
list.add(integer);
}
/**
* test
*/
// param是一个参数传递到 Predicate 接口的 test 方法
// 如果 n%2 为 0 test 方法返回 true
System.out.println("我是偶数");
eval(list,param->param%2==0);
System.out.println("-------------");
System.out.println("我是大于5的");
//如果 参数大于5 则返回为true
eval(list,param->param>5);
/**
* add方法
*/
//大于5 的数组
Predicate <Integer> filter1 = param->param>5;
//偶数数组
Predicate <Integer> filter2 = param->param%2==0;
list.removeIf(filter1.and(filter2));//移除 既大于5 又是偶数的数组
System.out.println("移除 既大于5 又是偶数的数组:最终数组"+list.toString());
/**
* negate 非
*/
list.removeIf(filter1.negate());//
System.out.println("输出大于5最终数组"+list.toString());
/**
* isEqual 判等
*/
Predicate<Integer> filter3 = Predicate.isEqual(7);
list.removeIf(filter3);
System.out.println("移除7 后的最终数组"+list.toString());
}
public static void eval(List<Integer> list,Predicate <Integer> predicate ) {
for (Integer integer : list) {
if(predicate.test(integer)){
System.out.println(integer+" ");
}
}
}
}