函数式接口(FunctionalInterface)
- 只声明了一个抽象方法的接口称为函数式接口
- 可以在接口上添加注解(@FunctionalInterface)来判断此接口是否为函数式接口
/**
* Java内置的4大核心函数式接口
* 消费型接口:Consumer<T> void accept(T t)
* 供给型接口:Supplier<T> T get()
* 函数型接口:Function<T,R> R apply(T t)
* 断定型接口:Predicate<T> boolean test(T t)
*/
举两个例子看一下如何使用
/*
消费型接口实例
*/
@Test
public void test1(){
happyTime(500,money -> System.out.println("打完篮球买了一瓶水花了" + money));
}
public void happyTime(int money, Consumer<Integer> con){
con.accept(money);
}
/*
断定型接口实例
去除集合中
*/
@Test
public void test2(){
List<String> list = Arrays.asList("北京", "东京", "南京", "天津");
ArrayList<String> list1 = removeList(list, s -> s.contains("京"));
System.out.println(list1.toString());
}
public ArrayList<String> removeList(List<String> list, Predicate<String> pre){
ArrayList<String> returnList = new ArrayList<>();
for (String s : list){
if(pre.test(s)){
returnList.add(s);
}
}
return returnList;
}