当前位置: 代码迷 >> 综合 >> Java8函数式编程接口:Consumer、Supplier、Function、Predicate
  详细解决方案

Java8函数式编程接口:Consumer、Supplier、Function、Predicate

热度:81   发布时间:2023-09-11 04:51:51.0

https://blog.csdn.net/ll15982534415/article/details/117487198

开宗明义

java8的一个新特性就是在java.util.function中提供了四个函数式编程接口,分别是Consumer、Supplier、Function、Predicate。

其中,

  • consumer即消费接口,传入一个参数,并对其进行相应的操作(有点类似于lambda表达式);

  • supplier即供给接口,可以传入数据,作为一个容器

  • function即方法接口主要是用作数据类型之间的转换

  • predicate即判断接口,传入参数,而后返回判断的结果true/false

接下来仔细瞅瞅这四种接口的源码以及怎么使用它们。

庖丁解牛

consumer

源码

Consumer接口的源码只有两个方法,一个方法用来接收入口参数,另外一个是为了实现流式操作

@FunctionalInterface
public interface Consumer<T> {
       
<span class="token comment">/***接收一个泛型入参*/</span>
<span class="token keyword">void</span> <span class="token function">accept</span><span class="token punctuation">(</span><span class="token class-name">T</span> t<span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">/*** 是指在进行这个consumer之后,在将结果送进另外一个consumer,* 从而实现consumer的流式操作(一个接一个地进行)*/</span>
<span class="token keyword">default</span> <span class="token class-name">Consumer</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">T</span><span class="token punctuation">&gt;</span></span> <span class="token function">andThen</span><span class="token punctuation">(</span><span class="token class-name">Consumer</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token operator">?</span> <span class="token keyword">super</span> <span class="token class-name">T</span><span class="token punctuation">&gt;</span></span> after<span class="token punctuation">)</span> <span class="token punctuation">{<!-- --></span><span class="token class-name">Objects</span><span class="token punctuation">.</span><span class="token function">requireNonNull</span><span class="token punctuation">(</span>after<span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token keyword">return</span> <span class="token punctuation">(</span><span class="token class-name">T</span> t<span class="token punctuation">)</span> <span class="token operator">-&gt;</span> <span class="token punctuation">{<!-- --></span> <span class="token function">accept</span><span class="token punctuation">(</span>t<span class="token punctuation">)</span><span class="token punctuation">;</span> after<span class="token punctuation">.</span><span class="token function">accept</span><span class="token punctuation">(</span>t<span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token punctuation">}</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
  相关解决方案