Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter list by indexes

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?

like image 292
Nyavro Avatar asked Dec 03 '25 17:12

Nyavro


2 Answers

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.

like image 105
1gLassitude Avatar answered Dec 06 '25 09:12

1gLassitude


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).

like image 42
Sascha Kolberg Avatar answered Dec 06 '25 09:12

Sascha Kolberg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!