How do I filter list by indexes stored in another list? For instance I have the following list of values:
val list = List("a", "b", "c", "d", "e", "f")
and the list of indexes:
val indexes = List(1,2,5)
I want to get the following list:
List("b", "c", "f)
What is the most idiomatic way?
To avoid creating too many intermediary objects, you could write
indexes.map(list.lift).flatten
With an indexed sequence, lookup time in the list would be constant. It's both idiomatic and efficient. If list is of type List, which has lookup time is O(n), then the you have O(m * n), where m is the length of indexes, and n is the length of the list.
The difference between this and indexes.map(list) is whether or not you want to throw an exception if an index is not found in the list.
list.lift creates a function that takes an index and returns Some(value) if it exists, and None otherwise. The flatten method flattens the resulting List of Option. It removes all the None results, and extracts the values from the Some results.
You can do just:
indexes.map(list)
which is short for
indexes.map(index => list.apply(index))
Though, I would recommend to use something that is optimized for indexes (IndexedSeq).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With