Java函数式接口

1. Consumer接口

接受一个固定类型的参数,无返回值

//使用方式
// 1 使用consumer接口实现方法
Consumer<String> consumer = new Consumer<String>() {
            @Override
            public void accept(String s) {
                System.out.println(s);
            }
        };
// 2 lambda函数方式
Consumer<String> consumer = (s) -> System.out.println(s);
// 3 使用方法引用,方法引用也是一个consumer
stream = Stream.of("aaa", "bbb", "ddd", "ccc", "fff");
Consumer consumer2 = System.out::println;
stream.forEach(consumer);

2. Supplier 接口

返回一个固定类型的对象 无参数

//① 使用Supplier接口实现方法,只有一个get方法,无参数,返回一个值
Supplier<Integer> supplier = new Supplier<Integer>() {
    @Override
    public Integer get() {
        //返回一个随机值
        return new Random().nextInt();
    }
};
//② 使用lambda表达式,
supplier = () -> new Random().nextInt();

//③ 使用方法引用
Supplier<Double> supplier2 = Math::random;

3.Function 接口

// function的作用是转换,将一个值转为另外一个值
Function<String, Integer> function = new Function<String, Integer>() {
    @Override
    public Integer apply(String s) {
        return s.length();//获取每个字符串的长度,并且返回
    }
};
// lambda 写法
Function<String, Integer> function =  (s)->{
    return s.length();
}

本文作者:Joe's blog

本文链接:https://www.cnblogs.com/rise0111/p/17339627.html

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   FromZeroToOne  阅读(37)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· 葡萄城 AI 搜索升级:DeepSeek 加持,客户体验更智能
· 什么是nginx的强缓存和协商缓存
· 一文读懂知识蒸馏
点击右上角即可分享
微信分享提示
💬
评论
📌
收藏
💗
关注
👍
推荐
🚀
回顶
收起
  1. 1 404 not found REOL
404 not found - REOL
00:00 / 00:00
An audio error has occurred.