【问题标题】:Scala: Take List[People] and Convert it to a Map[String, List[People]]Scala:获取 List[People] 并将其转换为 Map[String, List[People]]
【发布时间】:2016-06-15 20:55:40
【问题描述】:

我对 Scala 非常陌生,正在尝试弄清楚如何使用 Collections。如果我有一个 List[People],所有人都有名字,有没有办法把它变成 Map[Person.getName, List[People]]。

我试过了

list map (t => t.getName() -> t) toMap, 

但这只会返回一个地图[姓名,人物]。我该怎么做?

提前致谢。

【问题讨论】:

    标签: scala dictionary collections


    【解决方案1】:

    groupBy 将采用 List[People] 并根据您提供的“鉴别器函数”将其转换为 Map[String, List[People]],在这种情况下,该函数是从 Person 中选择名称。

    scala> case class Person(name: String, age:Int)
    defined class Person
    
    scala> val people = List(Person("Alice", 42), Person("Bob", 42))
    people: List[Person] = List(Person(Alice,42), Person(Bob,42))
    
    scala> people.groupBy(p => p.name)
    res0: scala.collection.immutable.Map[String,List[Person]] = Map(Bob -> List(Person(Bob,42)), Alice -> List(Person(Alice,42)))
    

    【讨论】:

      【解决方案2】:

      如果你想自己动手并了解它是如何工作的,你可以试试这个:

      scala> case class Person(name: String, surname: String, age:Int)
      defined class Person
      
      scala> val people = List(Person("Alice", "Wonderland", 42), Person("Bob", "Father", 42), Person("Bob", "Son", 20))
      people: List[Person] = List(Person(Alice,Wonderland,42), Person(Bob,Father,42), Person(Bob,Son,20))
      
      scala> val names = people.map(_.name).distinct
      names: List[String] = List(Alice, Bob)
      
      scala> names.map(n => n -> people.filter(_.name == n)).toMap
      res0: scala.collection.immutable.Map[String,List[Person]] = Map(Alice -> List(Person(Alice,Wonderland,42)), Bob -> List(Person(Bob,Father,42), Person(Bob,Son,20)))
      

      干杯

      【讨论】:

      • 这是一种非常缓慢的方法。 O(N^2),第二个map
      • @TheArchetypalPaul,是的,并没有考虑性能,只是一种操纵信息的替代方式,可能有助于操作人员对其进行推理。 groupBy 绝对更简洁高效。干杯
      猜你喜欢
      • 2016-07-21
      • 2019-09-10
      • 1970-01-01
      • 2021-02-28
      • 1970-01-01
      • 1970-01-01
      • 2020-01-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多