Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Append Map(key, Set[value]) in a Map to existing Key in Scala 2.11

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))
like image 609
Rohit Nimmala Avatar asked Jul 05 '19 14:07

Rohit Nimmala


1 Answers

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))
like image 50
Mario Galic Avatar answered Nov 15 '22 04:11

Mario Galic