Vladimir Kostyukov
Vladimir Kostyukov

Reputation: 2552

Convert Scala's list into map with indicies as keys

All I wanted to do is to convert the following:

List(2, 4, 6, 8, 10) to Map(0 -> 2, 1 -> 4, 2 -> 6, 3 -> 8, 4 -> 10 ). In other words, map index to value. It should be very easy, but I'm missing something.

Can anyone suggest a simple way to do that?

UPD: Just to generalizate the solution. Let say that I need to perform an additional transormation of values. For example, to wrap it with List(_). In our case:

List(2, 4, 6, 8, 10) -> Map(0 -> List(2), 1 -> List(4), 2 -> List(6), 3 -> List(8), 4 -> List(10))

Upvotes: 12

Views: 8900

Answers (3)

Fynn
Fynn

Reputation: 4873

UPD: In case you want to transform the values, you can either use one of the solutions that have already been posted and then use the map's mapValues or you could apply the transformation beforehand:

List(2, 4, 6, 8, 10).zipWithIndex.map { case (v, i) => i -> List(v) }.toMap
res0: Map[Int,List[Int]] = Map(0 -> List(2), 1 -> List(4), 2 -> List(6), 3 -> List(8), 4 -> L
ist(10))

Upvotes: 5

Debilski
Debilski

Reputation: 67838

List(2, 4, 6, 8, 10).zipWithIndex.map(_.swap).toMap

Upvotes: 20

om-nom-nom
om-nom-nom

Reputation: 62835

val xs = List(2, 4, 6, 8, 10)
(xs.indices zip xs).toMap
// Map(0 -> 2, 1 -> 4, 2 -> 6, 3 -> 8, 4 -> 10)

Upvotes: 18

Related Questions