首页 > 解决方案 > 如何计算 Scala 混合对象序列中的每种类型/种类的对象

问题描述

我有一个颜色对象序列,比如说Seq[Color]

[
    {
        "color": "red"
    },
    {
        "color": "yellow"
    },
    {
        "color": "yellow"
    },
    {
        "color": "white"
    }
]

我想要得到的是每种颜色的计数,作为一个对象,比如ColorCount,如下所示

{
    "red": 1,
    "yellow": 2,
    "white": 1
}

现在我能想到的是如下所示。我想知道是否有更优雅的方式来处理它。

val redCount = colors.count( e => e.color == 'red') 
val yellowCount = colors.count( e => e.color == 'yellow') 
val whiteCount = colors.count( e => e.color == 'white') 

val colorCount = ColorCount(redCount, yellowCount, whiteCount)

标签: scalafunctional-programming

解决方案


假设颜色定义如下:

sealed trait Color
object Color {
  final case object Red extends Color
  final case object Yellow extends Color
  final case object White extends Color
}

这样的颜色计数

final case class ColorCount(redCount: Int, yellowCount: Int, whiteCount: Int)

你有一个颜色列表( ) 然后,您可以使用 val colors: List[Color] = ???
groupBy

// For 2.12-
val counts = colors.groupBy(identity).mapValues(_.size)
// For 2.13+
val counts = colors.groupMapReduce(identity)(_ => 1)(_ + _)

最后将它们counts转换为ColorCount

val result = ColorCount(
  redCount = counts.getOrElse(key = Color.Red, default = 0),
  yellowCount = counts.getOrElse(key = Color.Yellow, default = 0),
  whiteCount = counts.getOrElse(key = Color.White, default = 0),
)

推荐阅读