【问题标题】:Creating Map[String, Map[String, Object]] from List[Object]从 List[Object] 创建 Map[String, Map[String, Object]]
【发布时间】:2016-07-12 19:52:26
【问题描述】:

我刚刚习惯了 Scala,而且我已经

case class Person(name: String, birthPlace: String, hairColor: String)

我知道应该有一种将 List[Person] 转换为的好方法

Map[Name, Map[Birthplace, Person]]

但是,我不知道该怎么做。

我们将不胜感激。

【问题讨论】:

  • 只是一个一般性问题:为什么不存储 2 个单独的地图(假设多个人可以拥有同一个出生地)? Map[Name,List[Person]] 和 Map[Birthplace,List[Person]] 然后 resultPersonListA.intersect(resultPersonListB) ? imo 的优点是您可以直接访问这两个地图?

标签: scala dictionary collections


【解决方案1】:

可能有不止一个人具有相同的姓名和出生地,因此此类事情的更好数据类型是Map[String, Map[String, Seq[Person]]。 您可以使用.groupBy 创建它:

    list
      .groupBy(_.name)
      .mapValues(_.groupBy(_.birthplace))

如果您想忽略多次出现,可以通过在末尾添加以下内容来丢弃它们:

      .mapValues(_.mapValues(_.head))

【讨论】:

    猜你喜欢
    • 2018-09-22
    • 2020-08-01
    • 1970-01-01
    • 2021-04-29
    • 2020-01-26
    • 1970-01-01
    • 2018-04-26
    • 2015-11-21
    • 1970-01-01
    相关资源
    最近更新 更多