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?
More generally you can use views; then the collection is only iterated once and all three operations are applied as you go: