Rodrigo Sasaki Rodrigo Sasaki - 6 months ago 26
Scala Question

Get the most recent location of many users

I believe there must be a better way to ask this question, but I couldn't think of it.

Consider this case class:

case class UserLocation(id: Int, dateTime: DateTime, lat: Double, lon: Double)

I have a
with the history of all locations of all users, and I would like to filter this list to only have the most recent location from each of them.

Here is how I did it:

implicit def dateTimeOrdering: Ordering[DateTime] = Ordering.fromLessThan(_ isAfter _)

val locations: List[UserLocation] = bigListOfUserLocations()
val groupedById = locations.groupBy(
val sortedByDate =
val finalList =

This works, but what I would like to know is if there is a better way to do this, improving performance and/or readability

IMPORTANT: This is mostly an academic question, I would like to know the most performatic or most idiomatic way of achieving this on manipulating lists, so suggestions like "try xyz on the database before you receive the list" won't be helpful


You're basically there, but you can reduce the last two operations to one with:

val finalList =

This is more readable, and more performant, since you just find the biggest item in the group wihtout needing to put the rest in order.