如何从地图中的所有键返回所有地址值

时间:2017-07-25 03:54:21

标签: scala

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)

3 个答案:

答案 0 :(得分: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))

答案 1 :(得分:0)

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

答案 2 :(得分: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(..))