【问题标题】:Convert List of Object to Map with duplicate key将对象列表转换为具有重复键的映射
【发布时间】:2017-03-02 10:25:55
【问题描述】:

我有一个如下所示的课程:

case class Person(id : String, name : String, refId : String) {}

我有一个人员列表。

我想要一张带有
的地图 键 = refId
value = List[Person] 具有相同 refId (重复键)

我做了什么:

val persons = getPersons() // get the List from somewhere
val refMap = new mutable.HashMap[String,Seq[Person]]()
for (person<- persons){
  refMap.put(person.refId,refMap.getOrElse(person.refId,new ArrayBuffer[Person]) :+ person)
}

那是我的第一个想法,它很有效,但我想要一些更像 Scala 的东西或者看起来更好的东西。你有什么想法吗?

我也试过这里写的:Convert List of tuple to map (and deal with duplicate key ?)

但他们使用元组,我也无法完成这项工作。 我也尝试过先将我的列表映射到元组,但是
1. 我不想在不需要时对 List 进行 2 次迭代(1 次创建元组,1 次创建地图。
2. 我试过了,但我也用元组失败了。

任何对更好代码的帮助都会很好。

【问题讨论】:

    标签: scala list dictionary duplicates


    【解决方案1】:

    试试groupBy:

    getPersons().groupBy(_.refId): Map[String, List[Person]]
    

    【讨论】:

      猜你喜欢
      • 2020-10-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-25
      • 2016-02-18
      • 1970-01-01
      • 2018-06-26
      • 1970-01-01
      相关资源
      最近更新 更多