user1553248
user1553248

Reputation: 1204

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.

Upvotes: 1

Views: 326

Answers (1)

Nikita Volkov
Nikita Volkov

Reputation: 43310

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.

Upvotes: 6

Related Questions