I have a list
val data = List(2, 4, 3, 2, 1, 1, 1,7)
with which I want to create a map such that values in above list are keys to new one with indeces as new values I tried
scala> data.zipWithIndex.toMap
res5: scala.collection.immutable.Map[Int,Int] = Map(1 -> 6, 2 -> 3, 7 -> 7, 3 -> 2, 4 -> 1)
but strangely it gives res5(1) as 6 but I want it to be 4.
I could solve it by
data.zipWithIndex groupBy (_._1) mapValues (w=>w.map(tuple=>tuple._2) min)
but is there any way I can pass a function f to toMap so that it creates map in desired way.
toMapis going to add each pair to the map in the order of the zipped list, and when you add a mappingk -> vto a map that already contains ak, the old value is simply replaced.An easy fix is just to reverse the list after zipping the indices and before converting to a map:
Now the mappings
1 -> 6and1 -> 5will be added before1 -> 4, which means1 -> 4is the one you'll see in the result.