Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 909
Vladimir Kostyukov Avatar asked Jul 24 '13 08:07

Vladimir Kostyukov


2 Answers

List(2, 4, 6, 8, 10).zipWithIndex.map(_.swap).toMap
like image 74
Debilski Avatar answered Sep 25 '22 20:09

Debilski


val xs = List(2, 4, 6, 8, 10)
(xs.indices zip xs).toMap
// Map(0 -> 2, 1 -> 4, 2 -> 6, 3 -> 8, 4 -> 10)
like image 24
om-nom-nom Avatar answered Sep 23 '22 20:09

om-nom-nom