List to map conversion

Hi, I’m looking for the best way to do the following:

List('a','b','c'){ case (v,i) => (i,v) }.toMap
res9: scala.collection.immutable.Map[Int,Char] = Map(0 -> a, 1 -> b, 2 -> c)

The below is where you use a property of the values (I don’t need to do this):

The below (towards the bottom) says you need to convert each to tuples and then to a map:

I do this in my method but it seems there could be a better way? (I don’t need optimal code e.g. breakout). Thanks.

I’d say your code is fine. In your special case of converting a list to a map from index to element, you could also use:

val list = List('a','b','c')
(1 to list.size).zip(list).toMap

which is basically the same but zips the index from the left, so you don’t need to turn it around.

But also note, that if your goal is just to have efficient index-based lookup, converting your List to an
IndexedSeq with .toIndexedSeq is better.

Or Iterator.from(0).zip(list).toMap which prevents the list.size linear complexity and all the intermediary datastructures.