Java 8中map和flatMap方法的区别是什么? [英] What's the difference between map and flatMap methods in Java 8?

查看:1740
本文介绍了Java 8中map和flatMap方法的区别是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java 8中, Stream.map Stream.flatMap 方法?

In Java 8, what's the difference between Stream.map and Stream.flatMap methods?

推荐答案

地图 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 操作采用函数,为输入流中的每个值调用并生成一个结果值,发送到输出流。

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 的值,然后将其发送到输出。鉴于这是流库,一种表示任意数量的返回值的特别方法是mapper函数本身返回一个流!映射器返回的流中的值将从流中排出并传递到输出流。每次调用mapper函数返回的值的clumps在输出流中根本不被区分,因此输出被称为平坦化。

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆