简体   繁体   中英

Scala iterate through two sequences and append to a list

I have the following method signature which aims to combine elements from two different sequences:

def newMap(local: Seq[String], passed: Seq[(String, Int)]): Map[String, Int] = {


}

In this case, the strings from the values local should be keys for a default value 0. Would it be possible to use a for-comprehension to loop through both of these sequence simultaneously, with a condition that adds a default 0 value for the first sequence in the map? I am also trying not to make use of mutable variables here.

def newMap(local: Seq[String], passed: Seq[(String, Int)]): Map[String, Int] = 
  (local.view.map((_, 0)) ++ passed.view).toMap

In the code above with view we first convert the input collections into their lazy wrappers, which instead of performing all the following operations right away accumulate them and only perform them when forced into some strict version. This allows us to perform all the operations ( map , ++ , toMap ) in a single traversal under the hood. The final toMap forces our lazy collection of pairs into a strict Map .

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