scala - 在 scala 中对 tuples2 列表进行分组的更好、更有效的方法

标签 scala group-by grouping scala-collections

我有 Scala Tuples2 的列表,我必须将它们分组。我目前使用以下方式来执行它。

var matches:List[Tuple2[String,Int]]
var m = matches.toSeq.groupBy(i=>i._1).map(t=>(t._1,t._2)).toSeq.sortWith(_._2.size>_._2.size).sortWith(_._2.size>_._2.size)

上面的分组给了我 Seq[(String,Seq[(String,Int)])] 但我想要 Seq[(String,Seq[Int])]

我想知道是否有更好、更有效的方法。

最佳答案

首先,一些想法:

// You should use `val` instead of `var`
var matches: List[Tuple2[String, Int]] = List("a" -> 1, "a" -> 2, "b" -> 3, "c" -> 4, "c" -> 5)
var m = matches
  .toSeq                            // This isn't necessary: it's already a Seq
  .groupBy(i => i._1)
  .map(t => (t._1, t._2))           // This isn't doing anything at all
  .toSeq
  .sortWith(_._2.size > _._2.size)  // `sortBy` will reduce redundancy
  .sortWith(_._2.size > _._2.size)  // Not sure why you have this twice since clearly the 
                                    // second sorting isn't doing anything...

所以试试这个:

val matches: List[Tuple2[String, Int]] = List("a" -> 1, "a" -> 2, "b" -> 3, "c" -> 4, "c" -> 5)
val m: Seq[(String, Seq[Int])] = 
  matches
    .groupBy(_._1)
    .map { case (k, vs) => k -> vs.map(_._2) }  // Drop the String part of the value
    .toVector
    .sortBy(_._2.size)
println(m) // Vector((b,List(3)), (a,List(1, 2)), (c,List(4, 5)))

关于scala - 在 scala 中对 tuples2 列表进行分组的更好、更有效的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22125512/

相关文章:

REST:按相关资源的属性过滤主要资源

sql - 甲骨文 SQL ORA-00937 : not a single-group group function

sql - CTE 未按预期表现的每周汇总

r - 为什么此 dplyr() 分组代码在 base R 中有效,但在 Shiny 中运行时却无效?

scala - 用于理解的 future 。检测故障

scala - isInstanceOf 使用路径相关类型

xml - 阻止 Scala 解析 XML

scala - 如何使用 shapeless 将字段从一个类复制到另一个不同的类

mysql - SQL group by 合并结果

python - 在 Pandas 中使用 groupBy 时如何进行加权求和