使用value在可变映射中查找键

时间:2018-03-07 06:52:36

标签: scala scala-collections

我们有案例类Item和categoryMap,如下所示:

case class Item(id: Int, name: String)

val categoryMap = scala.collection.mutable.Map[CategoryId: Int, List[Item]]()

我们怎样才能在' categoryMap'中找到CategoryId - 键。如果我们有id Item

2 个答案:

答案 0 :(得分:1)

id到类别(省略Item的一些不相关字段)构建另一个地图:

case class Item(id: Int, name: String)

val categoryMap = scala.collection.mutable.Map[Int,List[Item]](
  2 -> List(Item(42, "foo"), Item(34, "bar")),
  3 -> List(Item(9824, "baz"), Item(9836, "oofzab"))
)

val itemIdToCategory = (for {
  (k, v) <- categoryMap.toList
  id <- v.map(_.id)
} yield (id, k)).toMap

println(itemIdToCategory(42))
println(itemIdToCategory(34))
println(itemIdToCategory(9824))
println(itemIdToCategory(9836))

打印:2 2 3 3

答案 1 :(得分:0)

请尝试以下代码:

case class Item(id: Int, name: String)
val item1 = List(Item(1001, "HP"), Item(1002, "Dell"))
val item2 = List(Item(1003, "Fish1"), Item(1004, "Fish2"))
val categoryMap = scala.collection.mutable.Map[Int, List[Item]](100 -> item1,101 -> item2)
val catmap = categoryMap.flatMap { case (key, value) => value.map(_.id -> key) }
println(catmap.getOrElse(1001, null))
  

输出:100