Java8 4大函数接口 实例

Java8 4大函数接口
最近在学习Java8新特性,看到了lambda 表达式的强大 ,通过几个简单实例演示4大核心函数接口的使用!

    /**
     * Predicate 断言型接口
     * 获取长度大于4的数据
     */
    @Test
    public void testPredicate() {
        preStr(Arrays.asList("zhangsan", "lisi", "wangwu"), x -> x.length() > 4)
                .forEach(x -> System.out.println(x));
    }

    public List preStr(List<String> listStr, Predicate<String> predicate) {
        List<String> list = new ArrayList<>();
        for (String str : listStr) {
            if (predicate.test(str)) {
                list.add(str);
            }
        }
        return list;
    }

输出结果: 

zhangsan
wangwu
    /**
     * Supplier 供给型接口
     * 输出9个 两位随机数
     */
    @Test
    public void testSupplier() {
        List<Integer> listNum = supplier(9, () -> (int) (Math.random() * 100));
        listNum.forEach(x -> System.out.println(x));
    }

    public List<Integer> supplier(int num, Supplier<Integer> supplier) {
        List<Integer> list = new ArrayList<>();
        for (int i = 0; i < num; i++) {
            list.add(supplier.get());
        }
        return list;
    }

输出结果:

17
35
33
40
7
86
93
58
53
    /**
     * Function 函数型接口
     * 根据 , ; 把字符串进行分割
     */
    @Test
    public void testFunction() {

        String str = "a,b,c";
        List list = getStrArray(str, x -> Arrays.asList(x.split(",")));
        list.forEach(a -> System.out.println(a));
        System.out.println("---------------------");
        str = "d;e;f";
        list = getStrArray(str, x -> Arrays.asList(x.split(";")));
        list.forEach(a -> System.out.println(a));

    }

    public List getStrArray(String str, Function<String, List> function) {
        return function.apply(str);
    }

输出结果:

a
b
c
---------------------
d
e
f
    /**
     * Consumer 消费型接口
     * 传递一个参数 进行消费输出
     */
    @Test
    public void testConsumer() {
        consumer(20.00, x -> System.out.println("今天购物消费" + x));
    }

    public void consumer(Double money, Consumer<Double> consumer) {
        consumer.accept(money);
    }

输出结果:

今天购物消费20.0

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值