java8函数式编程学习(五)- 函数式接口


5. 函数式接口

5.1 概述

只有一个抽象方法的接口我们称之为函数接口。
JDK的函数式接口都加上了@FunctionalInterface注解进行标识,但是无论是否加这个注解,只要接口中只有一个抽象方法,都是函数式借口。不过可以用这个注解来验证我们自己实现的接口是否是函数式接口。

5.2 常见的函数式接口

Consumer 消费接口
根据其中的抽象方法的参数列表和返回值类型知道,我们可以在方法中传入的参数进行消费

@FunctionalInterface
public interface Consumer {

    /**
     * Performs this operation on the given argument.
     *
     * @param t the input argument
     */
    void accept(T t);

}

Function 计算转换接口
根根据其中的抽象方法的参数列表和返回值类型知道,我们可以对方法传入的参数进行计算或转换,把结果返回

@FunctionalInterface
public interface Function {

    /**
     * Applies this function to the given argument.
     *
     * @param t the function argument
     * @return the function result
     */
    R apply(T t);

}

Predicate 判断接口
根据其中的抽象方法的参数列表和返回值类型知道,我们可以对方法传入的参数进行条件判断,把布尔结果返回

@FunctionalInterface
public interface Predicate {

    /**
     * Evaluates this predicate on the given argument.
     *
     * @param t the input argument
     * @return {@code true} if the input argument matches the predicate,
     * otherwise {@code false}
     */
    boolean test(T t);

}

Supplier 生产型接口
根据其中的抽象方法的参数列表和返回值类型知道,我们在方法中创建对象,把创建好的对象返回

@FunctionalInterface
public interface Supplier {

    /**
     * Gets a result.
     *
     * @return a result
     */
    T get();

}

5.3 常用的默认方法

and 我们在使用Predicate接口时需要条件拼接判断,and方法相当于使用了&&来拼接两个条件

List authors = StreamDemo.getAuthors();
authors.stream()
    .filter(((Predicate) author -> author.getAge() > 10).and(author -> author.getName().length() > 1))
    //.filter(author -> author.getAge() > 1 && author.getName().length() > 1)
    .forEach(author -> System.out.println(author));

or 我们在使用Predicate接口时需要条件拼接判断,or方法相当于使用了||来拼接两个条件

List authors = StreamDemo.getAuthors();
authors.stream()
    .filter(((Predicate) author -> author.getAge() > 10).or(author -> author.getName().length() > 1))
    .forEach(author -> System.out.println(author));

negate 我们在使用Predicate接口时需要条件拼接判断,negate方法相当于非操作(取反)

authors.stream()
    .filter((((Predicate) author -> author.getAge() > 10).negate()))
    .forEach(author -> System.out.println(author));
// 实际场景下用法
test21(value -> value % 2 == 0, value -> value > 4);

public static void test21(IntPredicate predicate1, IntPredicate predicate2) {
    int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    for (int i : arr) {
        if (predicate1.and(predicate2).test(i)) {
            System.out.println(i);
        }
    }
}