关于函数式接口

2022-08-25  本文已影响0人  flyjar

我们知道使用Lambda表达式的前提是需要有函数式接口,而Lambda表达式使用时不关心接口名,
抽象方法名。只关心抽象方法的参数列表和返回值类型。因此为了让我们使用Lambda表达式更加的方
法,在JDK中提供了大量常用的函数式接口

所谓函数式接口,其实就是为我们提供一个回调方法,我们将具体实现的内容通过函数式结果,传入到一个方法中。
所以函数式接口一般都具有固定的格式,比如只返回,或者只消费,或者有返回也有销毁 ,或者做断言。所以java给我们提供了一系列的默认函数式接口,我们可以去调用

/**
* 1、这个函数式接口,提供了一个又返回也有消费的方法
*/
@FunctionalInterface
interface UserService {

    Long getSum(Integer[] array);
}


public class test {

    public static void main(String[] args) {
         // 2、我们给了这个函数式接口方法的具体实现,并将这个方法以对象的形式传入给了另一个方法
        getData((nums)-> Arrays.asList(nums).stream().collect(Collectors.summarizingInt(Integer::intValue)).getSum());
    }

    public static void getData(UserService userService) {

        Integer[] nums = {1, 12,3, 1, 21, 23, 12, 312, 3};

        System.out.println(userService.getSum(nums))

    }

}

以下四种是java提供的基础函数式接口。
重点:

在java.util.function包下有很多的函数式接口
函数式接口只能有一个抽象方法,但是可以有多个default实现方法和多个静态方法

@FunctionalInterface
public interface Supplier<T> {

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

@FunctionalInterface
public interface Consumer<T> {

    /**
     * Performs this operation on the given argument.
     *
     * @param t the input argument
     */
    void accept(T t);
}
@FunctionalInterface
public interface Function<T, R> {
    /**
     * Applies this function to the given argument.
     *
     * @param t the function argument
     * @return the function result
     */
    R apply(T t);
}
@FunctionalInterface
public interface Predicate<T> {
    /**
     * 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);
}
上一篇 下一篇

猜你喜欢

热点阅读