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

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

问题描述

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

解决方案

mapflatMap 都可以应用于 Stream> 并且它们都返回一个 Stream.不同之处在于 map 操作为每个输入值生成一个输出值,而 flatMap 操作为每个输入值生成任意数量(零个或多个)的值.

这反映在每个操作的参数中.

map 操作接受一个 Function,它为输入流中的每个值调用并产生一个结果值,该值被发送到输出流.>

flatMap 操作采用一个函数,该函数在概念上希望消耗一个值并生成任意数量的值.但是,在 Java 中,方法返回任意数量的值很麻烦,因为方法只能返回零或一个值.可以想象一个 API,其中 flatMap 的映射器函数接受一个值并返回一个数组或一个值的 List,然后将这些值发送到输出.鉴于这是流库,表示任意数量返回值的一种特别恰当的方式是让映射器函数本身返回流!映射器返回的流中的值从流中排出并传递到输出流.每次调用映射器函数返回的值的块"在输出流中根本没有区别,因此输出被称为扁平化".

典型用途是 flatMap 的映射器函数返回 Stream.empty() 如果它想发送零值,或者类似 Stream.of(a, b, c) 如果它想返回多个值.但当然可以返回任何流.

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

解决方案

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.

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.

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."

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天全站免登陆