java8之lambda四种基本的函数式接口

jdk8中提供了四中最基本的函数式接口供我们使用,减少我们编写额外的接口。

    Predicate:泛型单入参返回布尔值出参 Function:泛型单入参返回泛型出参 Supplier:无入参返回泛型出参 Consumer:泛型单入参无出参

这四种是使用最多的函数式接口,都是单参或无参。多入参的如BiFunction等函数式接口可以打开jdk包自行查找。

Predicate:

@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);
}


 @Test
    public void customPredicate(){
        predicate("hello",x-> x.contains("x"));
    }

    /**
     * 入参 --> true/false
     * @param str
     * @param t
     */
    public void predicate(String str, Predicate<String> t){
        if(t.test(str)){
            System.out.println("haha");
        }else {
            System.out.println("whats up");
        }
    }

Function:

@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);
}

    @Test
    public void customFunction(){
        System.out.println(function(10, x -> x * x));
    }

    /**
     * 入参 --> 出参
     */
    public int  function(int i, Function<Integer,Integer> f){
        return f.apply(i);
    }

Supplier:

@FunctionalInterface
public interface Supplier<T> {
    /**
     * Gets a result.
     * @return a result
     */
    T get();
}

    @Test
    public void customSupplier(){
        System.out.println(supplier(10, () -> new Random().nextInt(20)));
    }
    /**
     * 空参 --> 出参
     * @return
     */
    public int  supplier(int i, Supplier<Integer> s){
        return s.get();
    }

Consumer:

@FunctionalInterface
public interface Consumer<T> {

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

    @Test
    public void customConsumer(){
        consumer(10, (x) -> System.out.println(++x));
    }
    /**
     * 入参 --> 空参
     */
    public void  consumer(int i, Consumer<Integer> c){
         c.accept(i);
    }
经验分享 程序员 微信小程序 职场和发展