scala - Scala group on named Tuple to get min value
问题描述
I have a Seq of Named tuples as follows:
Seq[GeoDetails] where GeoDetails is of the type GeoDetails(geo_name: String, first_geo_time: Long)
In the Sequence, there can be multiple records for a single Geo and I want to write a function to Group by on geo_name and take the MIN value for first_geo_time. For e.g.
Input:
Seq(GeoDetails("cn", 1111111111111L), GeoDetails("mx", 2222222222222L), GeoDetails("mx", 3333333333333L), GeoDetails("cn", 4444444444444L))
Desired Output:
Seq(GeoDetails("cn", 1111111111111L), GeoDetails("mx", 2222222222222L))
I think using groupBy and foldLeft can do the job but I'm new to Scala and would appreciate some help on this. I want to get the output with the case class being maintained
解决方案
类似(Scala 2.13):
val list = Seq(GeoDetails("cn", 1111111111111L), GeoDetails("mx", 2222222222222L), GeoDetails("mx", 3333333333333L), GeoDetails("cn", 4444444444444L))
list.groupBy(_.geo_name).view.mapValues(el => el.sortBy(_.first_geo_time).head).toList
推荐阅读
- rust - 使用 tonic 和 rust 创建 grpc 客户端
- python - 从 3D 数组中的行中删除索引
- c++ - Nsight 无法捕获所有无绑定图像
- sql - 雪花函数中的 DDL 语句
- python - get() 接受 1 个位置参数,但在尝试覆盖 django 中的保存方法时给出了 2 个
- react-select - reactjs-select + react-google-places-autocomplete:如何使用地点进行初始化
- pytorch - 在 PyTorch 中计算两个相同大小的方阵的逐行点积的有效方法
- python - Python 请求:SSL 验证
- python - 使 spyder 使用进程内内核
- ruby-on-rails - rails 如何从表单提交中生成对象?