JDK8 四大核心函数式接口Function、Consumer、Supplier、Predicate

前言

我们知道Lambda表达式应用在函数式接口中,除了我们平时自己写的函数式接口外,源码中的哪些常用接口也可以使用呢?

函数型接口Function<T, R>

源码

 * @since 1.8
 */
@FunctionalInterface
public interface Function<T, R>{
R apply(T t);
}

用法:T 是入参,R是出参,结合lamdba表达式一起使用

Function<String, String> fun = e ->"hello:"+e;
fun.apply("freshman"))
消费型接口Consumer

源码

 * @since 1.8
 */
@FunctionalInterface
public interface Consumer<T> {
void accept(T t);
}

用法:有入参,没有入参

Consumer<Integer> fun = e ->System.out.println(e/1);;
fun.accept(0);
供给型接口Supplier

源码

 * @since 1.8
 */
@FunctionalInterface
public interface Supplier<T> {
    T get();
}

用法:没有入参,有出参

Supplier<Object> fn = ()-> new Object();
Object obj = fn.get();
断言型接口Predicate

源码

 * @since 1.8
 */
@FunctionalInterface
public interface Predicate<T> {
boolean test(T t);
}

用法:有入参,返回boolen值

Predicate<Integer> fn =(e)->10<e;
fn.test(10);
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值