2017-07-25 75 views
0
case class Company(name: String, locations: List[Location]) 
case class Location(name: String, address: String) 

val m = Map[String, Location](....) 

如何返回所有鍵的所有地址列表?如何返回地圖中所有鍵的所有地址值

這個我試過,到目前爲止,但它不工作:

val addressValues: List[String] = m.mavValues(x => x.locations) 

回答

0

val addressValues: List[String] = m.values.map(_.address).toList 看類型和apimapValues返回新的Map

1

你需要.map並獲得位置,這將給你Iterable[Location]

scala> val m = Map[String, Location]("prayagupd" -> Location("First hill", "England"), 
            "blankman" -> Location("Blank hill", "Blank States")) 
m: scala.collection.immutable.Map[String,Location] = Map(prayagupd -> Location(First hill,England), blankman -> Location(Blank hill,Blank States)) 

scala> m.map { case (name, location) => location } 
res10: scala.collection.immutable.Iterable[Location] = List(Location(First hill,England), Location(Blank hill,Blank States)) 

如果你需要的位置名稱,

scala> m.map { case (_, location) => location.name } 
res14: scala.collection.immutable.Iterable[String] = List(First hill, Blank hill) 

或者,你可以簡單地做.values這也給出Iterable[Location]

scala> m.values 
res2: Iterable[Location] = MapLike.DefaultValuesIterable(Location(First hill,England), Location(Blank hill,Blank States)) 
+0

在地圖上'values'函數返回的所有值,從而無需使用'map'了點。 –

0

Map上,.values函數返回所有值的Iterable

> val m1: Map[String, Location] = ??? 
> m1.values 
res0: Iterable[Location] = MapLike(Location(..)) 

或者,如果你有一個Map[String, Company]

> val m2: Map[String, Company] = ??? 
> m2.mapValues(_.locations).values.flatten 
res1: Iterable[Location] = List(Location(..)) 
相關問題