summerNight summerNight - 3 months ago 18
Scala Question

Scala filter a list based on a max value

I have the following MAP:

[
{ "animal": "dog", "age": 1},
{ "animal": "dog", "age": 2},
{ "animal": "dog", "age": 3},
{ "animal": "cat", "age": 1},
{ "animal": "cat", "age": 4},
{ "animal": "rabbit", "age": 9}
]


How do I return a result so that I get both dogs, cats and rabbits with the max age. Example:

[
{ "animal": "dog", "age": 3}, # oldest dog in DB
{ "animal": "cat", "age": 4}, # oldest cat in DB
{ "animal": "rabbit", "age": 9} # oldest rabbit in DB

]


I am trying to get this using two scala .map() aggregation but no success so far.

Answer

Assuming a case class like case class Pet(animal: String, age: Int):

list.groupBy(_.animal).values.map(_.maxBy(_.age)).toList

For List[BSONDocument], same concept:

list.groupBy(_.getAs[String]("animal")).values.map(_.maxBy(_.getAs[Int]("age"))).toList
Comments