如何根据某种方法的结果收集集合中的元素?
假设我们有一个根据某种顺序排序的值列表。我们还有映射到这些值的元素映射。我们希望从映射中获取元素的集合,其顺序与其键在列表中的顺序相同。执行此操作的一个简单方法是:
val order = Seq("a", "b", "c")
val map = Map("a" -> "aaa", "c" -> "ccc")
val elems = order.map(map.get(_)).filter(_.isDefined).map(_.get)
但是程序需要迭代集合 3 次。是否可以更有效地实现此功能?特别是,是否可以使用 collect 方法来做到这一点?
Suppose we have a list of values sorted according to some ordering. We also have a map of elements mapped to these values. We want to obtain a collection of elements from the map in the same order as their keys are in the list. A straightforward method to do this is:
val order = Seq("a", "b", "c")
val map = Map("a" -> "aaa", "c" -> "ccc")
val elems = order.map(map.get(_)).filter(_.isDefined).map(_.get)
However the program needs to iterate over the collection three times. Is it possible to implement this functionality more efficiently? In particular, is it possible to do this with collect method?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
好吧,标准的 Scala 映射也是 PartialFunction,所以你可以使用“collect”。
Well, a standard Scala map is also a PartialFunction, so you can use "collect".
如果您基于
Option
返回,那么这是可行的:当然,在这个特定示例中,
ordercollectmap
就足够了。If you base it on an
Option
return, then this works:Though, of course,
order collect map
is enough in this particular example.更一般地,您可以使用视图;那么该集合仅迭代一次,并且所有三个操作都会应用:
More generally you can use views; then the collection is only iterated once and all three operations are applied as you go:
您可以使用 flatMap 来实现这一点。这是一个例子:
这相当于
You can use flatMap for that. Here is an example:
This is equivalent to