Stream peek 与 map的区别
Posted 沛沛老爹
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Stream peek 与 map的区别相关的知识,希望对你有一定的参考价值。
一直用stream().map()方法。今天突然看到了IDEA的代码优化,帮忙自动给优化成了peek方法。一时感到比较好奇,然后就突突了一下。
老办法,先看下官方定义(源码)
peek
/**
* Returns a stream consisting of the elements of this stream, additionally
* performing the provided action on each element as elements are consumed
* from the resulting stream.
*
* <p>This is an <a href="package-summary.html#StreamOps">intermediate
* operation</a>.
*
* <p>For parallel stream pipelines, the action may be called at
* whatever time and in whatever thread the element is made available by the
* upstream operation. If the action modifies shared state,
* it is responsible for providing the required synchronization.
*
* @apiNote This method exists mainly to support debugging, where you want
* to see the elements as they flow past a certain point in a pipeline:
* <pre>@code
* Stream.of("one", "two", "three", "four")
* .filter(e -> e.length() > 3)
* .peek(e -> System.out.println("Filtered value: " + e))
* .map(String::toUpperCase)
* .peek(e -> System.out.println("Mapped value: " + e))
* .collect(Collectors.toList());
* </pre>
*
* <p>In cases where the stream implementation is able to optimize away the
* production of some or all the elements (such as with short-circuiting
* operations like @code findFirst, or in the example described in
* @link #count), the action will not be invoked for those elements.
*
* @param action a <a href="package-summary.html#NonInterference">
* non-interfering</a> action to perform on the elements as
* they are consumed from the stream
* @return the new stream
*/
Stream<T> peek(Consumer<? super T> action);
简单说是对当前stream进行操作,然后消耗流中的每个元素进行操作。
Consumer对象说明
@FunctionalInterface
public interface Consumer<T>
/**
* Performs this operation on the given argument.
*
* @param t the input argument
*/
void accept(T t);
它只有一个void方法,所以是没有返回值的。
map
/**
* Returns a stream consisting of the results of applying the given
* function to the elements of this stream.
*
* <p>This is an <a href="package-summary.html#StreamOps">intermediate
* operation</a>.
*
* @param <R> The element type of the new stream
* @param mapper a <a href="package-summary.html#NonInterference">non-interfering</a>,
* <a href="package-summary.html#Statelessness">stateless</a>
* function to apply to each element
* @return the new stream
*/
<R> Stream<R> map(Function<? super T, ? extends R> mapper);
map是要返回结果集的。
Function参数
@FunctionalInterface
public interface Function<T, R>
/**
* Applies this function to the given argument.
*
* @param t the function argument
* @return the function result
*/
R apply(T t);
结论
需要return的时候,用map。
不需要返回值的时候,用peek。
以上是关于Stream peek 与 map的区别的主要内容,如果未能解决你的问题,请参考以下文章
关于java stream流中的peek方法和foreach的自我理解:
java.util.stream map和flatmap的区别
Java8,stream().map().collect(Collectors.toList()).forEach()和stream().map().forEach()有什么区别?