zella zella - 26 days ago 8
Scala Question

How to merge two different collections with functional style

I have two collections:

val one = Seq(("1", 123), ("3", 555), ("2", 31))

val two = Seq("1", "4", "2")

I need to append second seq to first (order doesn't matter), example:

val result = Seq(("1", 123), ("2", 31), ("3", 555), ("4", 0)) //0 - constant

I can make it with transforming to set and iteration with contains check, but it's very ugly. How to implement this with correct "functional" style?

Answer Source

There are several possible ways. One of them is:

val oneKeys = one.map(_._1)
val result = one ++ two.filterNot(x => oneKeys.contains(x)).map(x => (x,0))

The expanation of methods:

val oneKeys = one.map(_._1) //gets the keys of each tuple from list `one`
two.filterNot(x => oneKeys.contains(x))  //selects the keys that list `one` does not contain
   .map(x => (x,0))                            //converts them into tuples by adding value `0`

++ operation basically merges two different Seq and returns the result