将列表转换为地图

时间:2016-08-08 20:46:11

标签: scala

我有以下类型:

case class Category(id: Int, name: String)
case class Product(id: Int, location: Location, categoryIdList: Option[List[Int]])

给出产品清单

val products:List[Product] = loadProducts()

如何将categoryId地图生成到位置?

Map[categoryId, Location]

所以我的方法看起来像这样:

def getMap(products: List[Product]): Map[Int, Location] = {
   ??
}

我需要以某种方式迭代categoryIdList的可选列表,然后使用Location属性创建一个映射。

3 个答案:

答案 0 :(得分:3)

要将Seq转换为Map,我们需要先将其转换为Seq[(Int,Location)],即Seq Tuple2 。只有这样,toMap方法才真正可用。

编辑:好的,这是基于列表中每个categoryId的实现,请注意,您不应该使用列表的选项,因为List的空状态只是一个空列表。

def getMap(products: List[Product]): Map[Int, Location] = {
   products.flatMap(toListTuple2).toMap
} 

def toListTuple2(product: Product): List[(Int, Location)] = {
  product.categoryIdList
    .getOrElse(List())
    .map(category => (category, product.location))
}

所以我们首先将我们的产品转换为categoryIdLocations的列表,然后将flatmap列为List的{​​{1}},然后通过调用(Int, Location)将其转换为Map

答案 1 :(得分:2)

这应该符合您的要求,但解决方案不能解决评论中提供的问题:

def getMap(products: List[Product]): Map[Int, Location] = {
  val locations = scala.collection.mutable.Map[Int, Location]()
  for {
    product <- products
    if product.categoryIdList.nonEmpty
    category <- product.categoryIdList.get
  } { 
    locations(category) = product.location
  }
  locations.toMap
}

答案 2 :(得分:0)

def getMap(products: List[Product]) = {
      products.map(p => (p.categoryIdList.getOrElse(List.empty), p.location))
              .flatMap(x => x._1.map(_ -> x._2))
              .toMap
}
相关问题