How to convert Tuples to Map with Set in Scala -


this first post. convert tuples map set in scala shown below.

set((1,"a"),(2,"b"),(1,"c")) 

map(1 -> set("a","c"), 2 -> set("b")) 

is there way make simpler?

if there missing information, please let me know.

i suggest check methods in scala collection library, it's pretty extensive , covers common cases one.

here how it:

set((1,"a"),(2,"b"),(1,"c"))   .groupby(_._1).mapvalues(_.map(_._2)) 

result:

res0: map[int,set[string]] = map(2 -> set(b), 1 -> set(a, c)) 

upd: @olegpyzhcov pointed out, mapvalues creates lazy view of original map, values reevaluated on every access. may inefficient if map repeatedly accessed after creation. solve problem may want materialize map in end. think simplest way following:

.mapvalues(_.map(_._2)).map(identity) 

@olegpyzhcov please correct me if there simpler/more efficient way.


Comments

Popular posts from this blog

Sort a complex associative array in PHP -

vb.net - How to ignore if a cell is empty nothing -

recursion - Can every recursive algorithm be improved with dynamic programming? -