简体   繁体   English

Scala遍历两个序列并追加到列表

[英]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? 在这种情况下,本地值中的字符串应该是默认值0的键。是否可以使用for-forhension来同时遍历这两个序列,并为第一个序列添加默认0值地图上的顺序? 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. 在上面带有view的代码中,我们首先将输入集合转换为它们的惰性包装器,而不是立即执行以下所有操作来累积它们,并且仅在强制使用某些严格版本时才执行它们。 This allows us to perform all the operations ( map , ++ , toMap ) in a single traversal under the hood. 这使我们能够在toMap一次遍历执行所有操作( map++toMap )。 The final toMap forces our lazy collection of pairs into a strict Map . 最终的toMap强制toMap的惰性集合放入严格的Map

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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