函数式接口

77 阅读2分钟

引言

所谓函数式接口,指的是只有一个抽象方法的接口

函数式接口可以用 @FunctionalInterface注解标识。

@FunctionalInterface
public interface Consumer<T> {
    void accept(T t);
}

Consumer

该接口只有一个参数,没有返回值,这个接口被称为消费型接口。

@FunctionalInterface
public interface Consumer<T> {
    void accept(T t);
}

Supplier

这是一个无参,有返回值得,返回类型为泛型类,这个接口称为供给型接口

@FunctionalInterface
public interface Supplier<T> {
    T get();
}

Predicate

传入一个参数,返回一个布尔值,断言型接口

@FunctionalInterface
public interface Predicate<T> {
    boolean test(T t);
}
  • and(Predicate other),相当于逻辑运算符中的&&,当两个Predicate函数的返回结果都为true时才返回true。
Predicate<String> predicate1 = s -> s.length() > 0;
 Predicate<String> predicate2 = Objects::nonNull;
 boolean test = predicate1.and(predicate2).test("&&测试");
 System.out.println(test);

or(Predicate other) ,相当于逻辑运算符中的||,当两个Predicate函数的返回结果有一个为true则返回true,否则返回false。

Predicate<String> predicate1 = s -> false;
 Predicate<String> predicate2 = Objects::nonNull;
 boolean test = predicate1.and(predicate2).test("||测试");
 System.out.println(test);

Function

传入一个参数,返回想要的结果

@FunctionalInterface
public interface Function<T> {
    R apply(T t);
}
Function<String, Integer> func = x -> x.length();
Integer apply = func.apply("cattle");
System.out.println(apply);

Lambda表达式结构

lambda 表达式可以具有零个或多个参数

可以显示声明参数的类型,可以有编译器根据上下文自动推断

       (a , b) -> {}
(int a ,int b) -> {} 

没有参数时可以使用括号

() -> {}

有且只有一个参数,可以不必使用括号

      a -> {}
    (a) -> {}
(int a) -> {}

Lambda 表达式只有一条语句时,大括号可以省略,返回值类型需与匿名函数保持一致

       (a , b) -> return a + b;
(int a ,int b) -> {return a + b;} 

方法引用

目标引用放在 :: 之前,目标引用提供的方法名称放在 :: 之后 ,即 目标引用::方法

Person::getAge()
//Function<T,R>,T表示传入类型,R表示返回类型
Function<UserInfo, Integer> getAge = UserInfo::getAge;
UserInfo userInfo = new UserInfo();
userInfo.setAge(10);
Integer apply = getAge.apply(userInfo);    //10


\