scala - 如何计算 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)
解决方案
假设颜色定义如下:
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),
)
推荐阅读
- python - python:如何将json转换为数据框
- python - 用 Python 保存数据帧字典的最佳文件格式是什么?
- ssl - 谷歌云平台静态网站 SLL 问题
- ruby-on-rails - 设计验证用户名的存在
- scala - 在 Scala 中将日期字符串转换为日期
- java - Junit 在 Bean 初始化之前创建测试数据模式
- spring-boot - Liquibase 不填充更改日志表中的上下文列
- c# - 找不到 Microsoft.SharePoint.Client.Sharing.SecurableObjectExtensions.GetSharingInformation() 方法
- reactjs - 由于神秘的语法错误,NPM 无法构建
- r - 如何在 dplyr 中计算迭代的逐行函数(例如增长率)>