# Convert a List of graph edges to a Map of neighboring nodes

What would be best way achieving this? Is it possible to use Immutable map?

import scala.collection.mutable.Map

/* Convert List of Edges to mapping Node -> List of Nodes */
def create_graph(edges: Array[Array[Int]]): Map[Int, List[Int]]  = {
val graph = Map[Int, List[Int]]();
for (i <- 0 until edges.length) {
val a = edges(i)(0)
val b = edges(i)(1)
if(graph contains a ) graph(a) = b::graph(a)
else graph(a) = List(b)
}
return graph
}


It is possible to achieve the same result with a scala.collection.immutable.Map:

def create_graph2(edges: Array[Array[Int]]): Map[Int, List[Int]]  = {
// group the tuples so that a -> Array((a, b1), (a, b2), (a, b3)...)
edges.groupBy(edge => edge(0))
// convert the array to target list of Ints, removing duplicates
.map{ case(key, edges) => (key, edges.map(_(1)).toSet.toList)}
}


Using the following test case:

val test1 = Array(Array(1, 2), Array(2, 3), Array(3, 4), Array(1, 5))
val result1 = create_graph(test1)
val result2 = create_graph2(test1)


The results are:

result1 = Map(2 -> List(3), 1 -> List(5, 2), 3 -> List(4))
result2 = Map(2 -> List(3), 1 -> List(2, 5), 3 -> List(4))

• I also found that in this case mapValues() instead of map() is very convenient. – Ski Nov 1 '16 at 23:18