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.