Question

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.

Was it helpful?

Solution

toMap is going to add each pair to the map in the order of the zipped list, and when you add a mapping k -> v to a map that already contains a k, 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:

data.zipWithIndex.reverse.toMap

Now the mappings 1 -> 6 and 1 -> 5 will be added before 1 -> 4, which means 1 -> 4 is the one you'll see in the result.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top