zella
zella

Reputation: 4685

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?

Upvotes: 1

Views: 339

Answers (2)

fcat
fcat

Reputation: 1251

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

Upvotes: 1

Shaido
Shaido

Reputation: 28322

I'm not sure what would be correct "functional" style. However, you can easily append these two collections together by using Map.

val result = (two.map((_,0)).toMap ++ one).toSeq

First all values in the two collection will be added with a value 0. The the one collection will be added, this will overwrite the values in the Map where the key is the same. After this you can simply convert the Map to a Seq which will give the desired result.

Upvotes: 5

Related Questions