Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert List of tuple to map (and deal with duplicate key ?)

Tags:

map

scala

I was thinking about a nice way to convert a List of tuple with duplicate key [("a","b"),("c","d"),("a","f")] into map ("a" -> ["b", "f"], "c" -> ["d"]). Normally (in python), I'd create an empty map and for-loop over the list and check for duplicate key. But I am looking for something more scala-ish and clever solution here.

btw, actual type of key-value I use here is (Int, Node) and I want to turn into a map of (Int -> NodeSeq)

like image 732
Tg. Avatar asked Nov 04 '11 23:11

Tg.


1 Answers

For Googlers that don't expect duplicates or are fine with the default duplicate handling policy:

List("a" -> 1, "b" -> 2).toMap // Result: Map(a -> 1, c -> 2) 

As of 2.12, the default policy reads:

Duplicate keys will be overwritten by later keys: if this is an unordered collection, which key is in the resulting map is undefined.

like image 57
Cory Klein Avatar answered Oct 07 '22 00:10

Cory Klein