简体   繁体   中英

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?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM