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 -&gt; List of Nodes */
def create_graph(edges: Array[Array[Int]]): Map[Int, List[Int]]  = {
    val graph = Map[Int, List[Int]]();
    for (i &lt;- 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 -&gt; Array((a, b1), (a, b2), (a, b3)...)
  edges.groupBy(edge =&gt; edge(0))
       // convert the array to target list of Ints, removing duplicates
       .map{ case(key, edges) =&gt; (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 -&gt; List(3), 1 -&gt; List(5, 2), 3 -&gt; List(4))
result2 = Map(2 -&gt; List(3), 1 -&gt; List(2, 5), 3 -&gt; List(4))