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))
List(2, 4, 6, 8, 10).zipWithIndex.map(_.swap).toMap
val xs = List(2, 4, 6, 8, 10)
(xs.indices zip xs).toMap
// Map(0 -> 2, 1 -> 4, 2 -> 6, 3 -> 8, 4 -> 10)
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