Java 8中的map()和flatMap()方法之间有什么区别?

编程入门 行业动态 更新时间:2024-10-28 13:17:05
本文介绍了Java 8中的map()和flatMap()方法之间有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

在Java 8中, Stream.map() 和 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()方法之间有什么区别?

本文发布于:2023-11-25 07:42:17,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1628903.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:有什么区别   方法   Java   map   flatMap

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!