Lambda表达式学习(二)

1. Java内置的四大核心函数式接口

在这里插入图片描述

  1. Consumer 消费型接口 消费对象

    void accept(T t);

public class Test {
    public static void helloWorld(String str, Consumer<String> consumer){
        consumer.accept(str);
    }
    public static void main(String[] args) {
        helloWorld("HelloWorld", (x)-> System.out.println(x));
    }
}
  1. Supplier 供给型接口 生成对象

    T get();

public class Test {
    public static void helloWorld(Supplier<Integer> supplier){
        System.out.println(supplier.get());
    }
    public static void main(String[] args) {
        helloWorld(() ->666);
    }
}
  1. Function<R,T> 函数型接口 指定特定功能

    R apply(T t);

public class Test {
    public static Integer helloWorld(Integer i, Function<Integer, Integer> function){
        return function.apply(i);
    }
    public static void main(String[] args) {
        Integer j = helloWorld(20,(x) ->{
            Integer in = 0;
            for (int i = 0; i < x; i++) {
                in++;
            }
            return in;
        });
        System.out.println(j);
    }
}
  1. Predicate 断言型接口 进行条件判断

    boolean test(T t);

public class Test {
    public static Boolean helloWorld(List<String> strs, Predicate<String> predicate){
        for (String str : strs) {
            if (predicate.test(str)) {
                return true;
            }
        }
        return false;
    }
    public static void main(String[] args) {
        List<String> strs = new ArrayList<>();
        strs.add("A");
        strs.add("B");
        strs.add("C");
        strs.add("D");
        strs.add("E");
        Boolean b = helloWorld(strs, (x) -> x.length() > 2);
        System.out.println(b);
    }
}

2. 核心函数子接口

图片来自与网络

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值