I'm trying to append a new value to the Set(Values) for an existing key, but it is replacing the existing value.
This is my input
val roads = Array(Array(0,1),Array(0,2),Array(1,2))
Expected output:
Map(0 -> Set(1,2),1 -> Set(2))
My Code:
val roads = Array(Array(0,1),Array(0,2),Array(1,2))
var adjMatrix:Map[Int,Set[Int]] = Map()
for(i <- 0 until roads.size; j <- 1 until roads(i).size){
adjMatrix += (roads(i)(0) -> Set(roads(i)(j)))
}
and when I do
adjMatrix.foreach(println)
I get below result, as there are two keys with 0 name, it replaces the (0,1) element at the 0th index
(1,Set(2))
(0,Set(2))
Try
roads
.groupBy(a => a(0))
.map { case (key, value) => key -> (value.flatten.toSet - key) }
which outputs
Map(1 -> Set(2), 0 -> Set(1, 2))
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