我们常用的一些接口Callable、Runnable、Comparator等在JDK8中都添加了@FunctionalInterface注解。(JDK8新加的注解)
JDK 1.8 API中包含了很多内置的函数式接口。有些是在以前版本的Java中大家耳 熟能详的,例如Comparator接口,或者Runnable接口。对这些现成的接口进行实 现,可以通过@FunctionalInterface 标注来启用Lambda功能支持。 此外,Java 8 API 还提供了很多新的函数式接口,来降低程序员的工作负担。有些 新的接口已经在Google Guava库中很有名了。如果你对这些库很熟的话,你甚至 闭上眼睛都能够想到,这些接口在类库的实现过程中起了多么大的作用。
函数式接口(Functional Interface)
就是一个有且仅有一个抽象方法,但是可以有多个非抽象方法的接口。
函数式接口可以被隐式转换为 lambda 表达式。
Lambda 表达式和方法引用(实际上也可认为是Lambda表达式)上。
JDK 1.8 新增加的函数接口,如 java.util.function.Supplier
package java.util.function;
/**
* Represents a supplier of results.
*
* <p>There is no requirement that a new or distinct result be returned each
* time the supplier is invoked.
*
* <p>This is a <a href="package-summary.html">functional interface</a>
* whose functional method is {@link #get()}.
*
* @param <T> the type of results supplied by this supplier
*
* @since 1.8
*/
@FunctionalInterface
public interface Supplier<T> {
/**
* Gets a result.
*
* @return a result
*/
T get();
}
应用
package com.taoshu.zhifu.workdemo.methodreference;
/**
* Created by yanyg on 2020-05-01.
*/
@FunctionalInterface
public interface BiPredicate<T,V> {
boolean test(T t,V v);
}
package com.taoshu.zhifu.workdemo.methodreference;
/**
* Created by yanyg on 2020-05-01.
* 类名::实例方法名
*/
public class BiPredicateMain {
public static void main(String[] args) {
BiPredicate<String, String> b = String::equals;
boolean test = b.test("abcd", "abcd");
System.out.println(test);
}
}