Supplier<T>和Consumer<T>

25 篇文章 0 订阅
@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等源码中也是常见的。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值