scala Iterable#map 与 Iterable#flatMap
Iterable
的 map
和 flatMap
函数有什么区别?
What is the difference between the map
and flatMap
functions of Iterable
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
以上都是正确的,但还有一件事很方便:
flatMap
将List[Option[A]]
转换为List[A]
code>,以及任何深入到None
的Option
,已删除。 这是超越使用null
的关键概念突破。The above is all true, but there is one more thing that is handy:
flatMap
turns aList[Option[A]]
intoList[A]
, with anyOption
that drills down toNone
, removed. This is a key conceptual breakthrough for getting beyond usingnull
.这是一个很好的解释:
http: //www.codecommit.com/blog/scala/scala-collections-for-the-easily-bored-part-2
以 list 为例:
Map 的签名是:
而 flatMap 的签名是
所以 flatMap 采用类型 [ A] 并返回一个可迭代类型 [B],而 map 接受一个类型 [A] 并返回一个类型 [B]
这也会让你知道 flatmap 会“展平”列表。
Here is a pretty good explanation:
http://www.codecommit.com/blog/scala/scala-collections-for-the-easily-bored-part-2
Using list as an example:
Map's signature is:
and flatMap's is
So flatMap takes a type [A] and returns an iterable type [B] and map takes a type [A] and returns a type [B]
This will also give you an idea that flatmap will "flatten" lists.
来自 scaladoc:
From scaladoc:
您可以在 for 推导式中更好地看到这一点:
这转换为:
for 中的每个迭代器都将被转换为“flatMap”,除了最后一个迭代器,它被转换为“map”。 这样,您将返回一个平面集合,而不是返回嵌套集合(等等缓冲区的数组列表)。 由正在生成的元素形成的集合——在本例中是整数列表。
You can see this better in for comprehensions:
this translates into:
Each iterator inside for will be translated into a "flatMap", except the last one, which gets translated into a "map". This way, instead of returning nested collections (a list of an array of a buffer of blah, blah, blah), you return a flat collection. A collection formed by the elements being yield'ed -- a list of Integers, in this case.
看这里:
http://www.codecommit。 com/blog/scala/scala-collections-for-the-easily-bored-part-2
“搜索 flatMap” - 那里有一个非常好的解释。 (基本上它是“展平”和“地图”的组合——来自其他语言的功能)。
Look here:
http://www.codecommit.com/blog/scala/scala-collections-for-the-easily-bored-part-2
"Search for flatMap" - there is a really good explanation of it there. (Basically it is a combination of "flatten" and "map" -- features from other languages).