Java新特性解读JDK8之函数式接口Consumer

网友投稿 878 2022-10-07

本站部分文章、图片属于网络上可搜索到的公开信息,均用于学习和交流用途,不能代表睿象云的观点、立场或意见。我们接受网民的监督,如发现任何违法内容或侵犯了您的权益,请第一时间联系小编邮箱jiasou666@gmail.com 处理。

Java新特性解读JDK8之函数式接口Consumer

Consumer作为消费型接口:有入参,无返回值

Consumer源码

package java.util.function;import java.util.Objects;/** * Represents an operation that accepts a single input argument and returns no * result. Unlike most other functional interfaces, {@code Consumer} is expected * to operate via side-effects. * *

This is a functional interface * whose functional method is {@link #accept(Object)}. * * @param the type of the input to the operation * * @since 1.8 */@FunctionalInterfacepublic interface Consumer { /** * Performs this operation on the given argument. * * @param t the input argument */ void accept(T t); }

Consumer使用

package com.example.functionalinterfacedemo;import java.util.Arrays;import java.util.List;import java.util.function.Consumer;public class ConsumerDemo { public static void main(String[] args) { //定义函数 Consumer consumer=obj->{ System.out.println(obj+"消费完成"); }; consume("jack",consumer); //简单写法 consume("tony",obj->{ System.out.println(obj+"消费完成"); }); //常用于集合遍历 List asList = Arrays.asList("11","22","33"); asList.forEach(obj->{System.out.println(obj);}); } public static void consume(String name,Consumer consumer){ consumer.accept(name);  }}

上一篇:linux如何查看docker是否启动成功
下一篇:linux中package是什么
相关文章

 发表评论

暂时没有评论,来抢沙发吧~