Java 8中的map()和flatMap()方法之间有什么区别? [英] What's the difference between map() and flatMap() methods in Java 8?
问题描述
在Java 8中, Stream.flatMap()
方法?
In Java 8, what's the difference between Stream.map()
and Stream.flatMap()
methods?
推荐答案
map
和flatMap
都可以应用于Stream<T>
,并且它们都返回Stream<R>
.区别在于map
操作为每个输入值生成一个输出值,而flatMap
操作为每个输入值生成任意数量(零个或多个)的值.
Both map
and flatMap
can be applied to a Stream<T>
and they both return a Stream<R>
. The difference is that the map
operation produces one output value for each input value, whereas the flatMap
operation produces an arbitrary number (zero or more) values for each input value.
这反映在每个操作的参数中.
This is reflected in the arguments to each operation.
map
操作采用Function
,它会为输入流中的每个值调用,并生成一个结果值,该结果值将发送到输出流.
The map
operation takes a Function
, which is called for each value in the input stream and produces one result value, which is sent to the output stream.
flatMap
操作采用的功能在概念上想消耗一个值并产生任意数量的值.但是,在Java中,方法返回任意数量的值很麻烦,因为方法只能返回零或一个值.可以想象一个API,其中flatMap
的映射器函数获取一个值并返回值的数组或List
,然后将其发送到输出.鉴于这是流库,一种表示任意数量的返回值的特别合适的方法是使映射器函数本身返回流!映射器返回的流中的值将从流中排出,并传递到输出流.在输出流中根本不会区分每次对映射器函数的调用返回的值的聚集",因此可以说输出已被扁平化".
The flatMap
operation takes a function that conceptually wants to consume one value and produce an arbitrary number of values. However, in Java, it's cumbersome for a method to return an arbitrary number of values, since methods can return only zero or one value. One could imagine an API where the mapper function for flatMap
takes a value and returns an array or a List
of values, which are then sent to the output. Given that this is the streams library, a particularly apt way to represent an arbitrary number of return values is for the mapper function itself to return a stream! The values from the stream returned by the mapper are drained from the stream and are passed to the output stream. The "clumps" of values returned by each call to the mapper function are not distinguished at all in the output stream, thus the output is said to have been "flattened."
flatMap
的映射器函数的典型用法是,如果要发送零值,则返回Stream.empty()
;如果要返回多个值,则类似于Stream.of(a, b, c)
.但是当然可以返回任何流.
Typical use is for the mapper function of flatMap
to return Stream.empty()
if it wants to send zero values, or something like Stream.of(a, b, c)
if it wants to return several values. But of course any stream can be returned.
这篇关于Java 8中的map()和flatMap()方法之间有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!