Hannah
Hannah

Reputation: 163

How to replace duplicate keys in a map

HI I am fairly new to scala programming. I want to know is there a way to rename the duplicate keys of map.

Suppose if I have a scala map here like

("a"->1,"b"->2,"c"->3,"d"->4,"a"->5,"c"->6,"e"->7,"a"->8)

I want the output in below format.The map should look like

("a_1"->1,"b"->2,"c_1"->3,"d"->4,"a_2"->5,"c_2"->6,"e"->7,"a_3"->8)

I just want to kind of assign a count system for each duplicate key occurrance.

So far I have been able to write a code which will give the no of occurance for a duplicate key.

var seq=map.toSeq
var cnt=seq.groupBy(_._1).mapValues(_.length)`

Upvotes: 1

Views: 254

Answers (1)

baitmbarek
baitmbarek

Reputation: 2518

You can try the following :

val seq = Seq("a"->1,"b"->2,"c"->3,"d"->4,"a"->5,"c"->6,"e"->7,"a"->8)

val cnt = seq.groupBy(_._1).flatMap{case (_, elems) => elems.zipWithIndex.map{case ((k,v), i) => s"${k}_${i+1}" -> v}}
print(cnt)

Output :

Map(c_1 -> 3, d_1 -> 4, a_2 -> 5, b_1 -> 2, a_3 -> 8, c_2 -> 6, a_1 -> 1, e_1 -> 7)

Note : if "b_1" should be formatted as "b", you can introduce a condition based on elems size

Edit :

Here's the code :

val cnt = seq.groupBy(_._1).flatMap{case (_, elems) => if(elems.size>1){ elems.zipWithIndex.map{case ((k,v), i) => s"${k}_${i+1}" -> v}} else elems}
println(cnt)
Map(e -> 7, c_1 -> 3, a_2 -> 5, b -> 2, a_3 -> 8, c_2 -> 6, a_1 -> 1, d -> 4)

Upvotes: 1

Related Questions