scala - combine two lists with same keys -


here's quite simple request combine 2 lists following:

scala> list1 res17: list[(int, double)] = list((1,0.1), (2,0.2), (3,0.3), (4,0.4))  scala> list2  res18: list[(int, string)] = list((1,aaa), (2,bbb), (3,ccc), (4,ddd)) 

the desired output as:

((aaa,0.1),(bbb,0.2),(ccc,0.3),(ddd,0.4)) 

i tried:

scala> (list1 ++ list2) res23: list[(int, any)] = list((1,0.1), (2,0.2), (3,0.3), (4,0.4),  (1,aaa), (2,bbb), (3,ccc), (4,ddd)) 

but:

scala> (list1 ++ list2).groupbykey  <console>:10: error: value groupbykey not member of list[(int,  any)](list1 ++ list2).groupbykey 

any hints? thanks!

here's quick one-liner:

scala> list2.map(_._2) zip list1.map(_._2) res0: list[(string, double)] = list((aaa,0.1), (bbb,0.2), (ccc,0.3), (ddd,0.4)) 

if unsure why works read on! i'll expand step step:

list2.map(<function>) 

the map method iterates on each value in list2 , applies function it. in case each of values in list2 tuple2 (a tuple 2 values). wanting access second tuple value. access first tuple value use ._1 method , access second tuple value use ._2 method. here example:

val mytuple = (1.0, "hello")   // tuple2 println(mytuple._1)            // prints "1.0" println(mytuple._2)            // prints "hello" 

so want function literal takes 1 parameter (the current value in list) , returns second tuple value (._2). have written function literal this:

list2.map(item => item._2) 

we don't need specify type item because compiler smart enough infer target typing. helpful shortcut can leave out item altogether , replace single underscore _. gets simplified (or cryptified, depending on how view it) to:

list2.map(_._2) 

the other interesting part 1 liner zip method. zip take 2 lists , combines them 1 list zipper on favorite hoodie does!

val = list("a", "b", "c") val b = list(1, 2, 3)  zip b     // returns ((a,1), (b,2), (c,3)) 

cheers!


Comments