加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

scala – flatten和flatMap(identity)之间有什么区别吗?

发布时间:2020-12-16 19:06:47 所属栏目:安全 来源:网络整理
导读:scala List(List(1),List(2),List(3),List(4))res18: List[List[Int]] = List(List(1),List(4))scala res18.flattenres19: List[Int] = List(1,2,3,4)scala res18.flatMap(identity)res20: List[Int] = List(1,4) 这两个功能有什么区别吗?何时使用一个而不
scala> List(List(1),List(2),List(3),List(4))
res18: List[List[Int]] = List(List(1),List(4))

scala> res18.flatten
res19: List[Int] = List(1,2,3,4)

scala> res18.flatMap(identity)
res20: List[Int] = List(1,4)

这两个功能有什么区别吗?何时使用一个而不是另一个?有任何权衡吗?

解决方法

您可以将flatMap(身份)视为地图(身份).flatten. (当然它没有这样实现,因为它需要两次迭代).

map(identity)为您提供相同的集合,因此最终它只与flatten相同.

我个人会坚持扁平化,因为它更短/更容易理解和设计来完全做到这一点.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读