Java 8 引入了函数接口( funtional interface ) 的概念,就是那些有且只有显式定义一个方法的接口。 函数接口为 Java 8 Lambda 表达式和方法引用提供目标类型, 用于适配该类型的 Lambda 表达式的参数类型和返回值类型。
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface FunctionalInterface {}
其定义为:
1.只能有一个抽象方法。
2.可以有多个静态方法和默认方法。
3.默认包含Object类的方法。
一、自定义函数实现:
@FunctionalInterface
public interface MyFunctionInterface {
void testMethod();
//静态方法
static void staticMethod(){
System.out.println("=====静态方法====");
}
default void defaultMethod(){
System.out.println("*****默认方法*****");
}
@Override
boolean equals(Object obj); // 来自 Object 类的方法
@Override
String toString(); // 来自 Object 类的方法
@Override
int hashCode(); // 来自 Object 类的方法
}
public class MyFunctionInterfaceTest {
public static void main(String[] args) {
MyFunctionInterface myfunctioninterface=()-> System.out.println("测试MyFunctionInterface");
//调用静态方法
MyFunctionInterface.staticMethod();
//调用自定义方法
myfunctioninterface.testMethod();
//调用默认方法
myfunctioninterface.defaultMethod();
}
}
结果为:
二、多参数自定义函数实现:
@FunctionalInterface
public interface ABCFunction<A,B,C> {
/**
* @param a 第一个参数
* @param b 第二个参数
* @return C 返回值
*/
C ABCMethod(A a,B b);
}
ABCFunction<String,String,String> ab = (a, b) -> a+b+"ccccc";
System.out.println(ab.ABCMethod("A","B"));
结果为:
三、Java8内置函数(java.util.function):
public class Empl implements Comparable<Empl>{
private String number;
private String name;
private String sex;
public Empl() {
}
public Empl(String number, String name, String sex) {
this.number = number;
this.name = name;
this.sex = sex;
}
/***
......省略对应的set和get 方法....
***/
@Override
public int compareTo(Empl empl) {
return empl.getNumber().compareTo(this.getNumber());
}
}
①消费型接口: Consumer< T> void accept(T t) 有参数,无返回值的抽象方法;
Consumer<Empl> empl = (e) -> System.out.println("Consumer===" +e.getName());
empl.accept(new Empl("1111","张三","男"));
结果为:
②供给型接口: Supplier < T> T get() 无参有返回值的抽象方法;
Supplier<Empl> emplSupplier = Empl::new;
Empl emp=emplSupplier.get();//等价于 new Empl
③断定型接口: Predicate<T> boolean test(T t):有参,但是返回值类型是固定的boolean。
Predicate<String> predicate = (s) -> s.length() > 0;
Boolean flag1=predicate.test("1111");
Boolean flag2=predicate.test("");
System.out.println("flag1=="+flag1);
System.out.println("flag2=="+flag2);
结果为:
④函数型接口: Function<T,R> R apply(T t)有参有返回值的抽象方法;
Function<String, Integer> toInteger = Integer::valueOf;
Function<String, String> ToString = toInteger.andThen(String::valueOf);
Integer integer=toInteger.apply("22222");
String str=ToString.apply("22222");