Supplier<T>和Consumer<T>

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

    /**
     * Returns a composed {@code Consumer} that performs, in sequence, this
     * operation followed by the {@code after} operation. If performing either
     * operation throws an exception, it is relayed to the caller of the
     * composed operation.  If performing this operation throws an exception,
     * the {@code after} operation will not be performed.
     *
     * @param after the operation to perform after this operation
     * @return a composed {@code Consumer} that performs in sequence this
     * operation followed by the {@code after} operation
     * @throws NullPointerException if {@code after} is null
     */
    default Consumer<T> andThen(Consumer<? super T> after) {
        Objects.requireNonNull(after);
        return (T t) -> { accept(t); after.accept(t); };
    }
}

这2个java8的函数式接口,都是带@FunctionalInterface注解的。

Supplier<T>是提供者,方法是get,也就是直接在get的时候才真正的调用该方法。比如:
@Test
    public void test(){
        Supplier<String> supplier = ()->getStudentCode();
        //其他逻辑
        //执行get方法的时候才执行getStudentCode方法
        String s = supplier.get();
        System.out.println(s);
    }

    private String getStudentCode(){
        return "11223334444";
    }
Consumer<T>是消费者,只有在执行accept方法的时候,才会执行。
@Test
    public void test(){
        Consumer<String> consumer = (value) -> {
            StudentInfoDTO studentInfoByCode = getStudentInfoByCode(value);
            System.out.println(JsonUtils.toJson(studentInfoByCode));
        };
        consumer.accept("11223334444");
    }

    public StudentInfoDTO getStudentInfoByCode(String code) {
        StudentInfoDTO dto=new StudentInfoDTO();
        dto.setEmail("111111");
        dto.setMobile("44444444");
        dto.setIdCard(code);
        return dto;
    }

在平时的工作中,这2个还是很常用的,比如在redis存储的时候,就可以使用。还有我们常用的一些集合ArrayList、Stream等源码中也是常见的。

经验分享 程序员 微信小程序 职场和发展