简体   繁体   English

Scala-根据键从地图读取值

[英]Scala- read values from a map based on keys

is there any better way to read values from a map based on keys if I have more keys in a map? 如果我在地图中有更多的键,有没有更好的方法从基于键的地图读取值?

currently I have a Map[String, List[String]] which can have more than 20 keys : 目前我有一个Map [String,List [String]] ,它可以有超过20个键

I am using below for retrieving values for each keys 我在下面使用它来检索每个键的值

val names= map.getOrElse("Name", List.empty)
.
.
.
val cities = map.getOrElse("City", List.Empty)

Please help If I can write this in better way. 请帮助如果我能以更好的方式写这个。

I very much doubt you're doing yourself any favors by replicating the Map data into local variables. 我非常怀疑你通过将Map数据复制到局部变量来做自己的任何好处。

One thing you could do is employ pattern matching to save some (not much) typing. 你可以做的一件事是采用模式匹配来节省一些 (不多)打字。

val knownKeys = List("Name", "City", "Country") // etc. etc.

val List(names
        ,cities
        ,countries
        // etc. etc.
        ) = knownKeys.map(data.getOrElse(_, List()))

A major drawback to this idea is that the list of keys has to be in the exact same order as the order of variables in the extraction. 这种想法的一个主要缺点是密钥列表必须与提取中的变量顺序完全相同。

A better idea is to give your Map its own default. 更好的想法是给你的Map自己的默认值。

val data = Map("City" -> List("NY","Rome")
              ,"Name" -> List("Ed","Al")
              // etc. etc.
              ).withDefaultValue(List.empty[String])

Then you don't need .getOrElse() . 那你就不需要.getOrElse()

data("City")     // res0: List[String] = List(NY, Rome)
data("Airport")  // res1: List[String] = List()

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

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