我有以下地图:
[
{ "animal": "dog", "age": 1},
{ "animal": "dog", "age": 2},
{ "animal": "dog", "age": 3},
{ "animal": "cat", "age": 1},
{ "animal": "cat", "age": 4},
{ "animal": "rabbit", "age": 9}
]
如何返回结果,以便使狗,猫和兔子的年龄都达到最大。例子:
[
{ "animal": "dog", "age": 3}, # oldest dog in DB
{ "animal": "cat", "age": 4}, # oldest cat in DB
{ "animal": "rabbit", "age": 9} # oldest rabbit in DB
]
我正在尝试使用两个scala .map()聚合来实现此操作,但到目前为止没有成功。
假设一个像这样的案例类case class Pet(animal: String, age: Int)
:
list.groupBy(_.animal).values.map(_.maxBy(_.age)).toList
对于List[BSONDocument]
,相同的概念:
list.groupBy(_.getAs[String]("animal")).values.map(_.maxBy(_.getAs[Int]("age"))).toList
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句