I have the following input:
case class Client(key: String, time: Option[Instant], bool: Boolean)
val l = List (
Client("87658763", Some(Instant.EPOCH), false),
Client("87658769", Some(Instant.EPOCH), false),
Client("87658769", Some(Instant.EPOCH), true)
)
For context, this data is the result of concatenated Lists from two API calls - one to get all Clients, and one to specifically get all Clients where bool is true.
I want the info to be distinct on the key and time. Also, where there are multiple Clients with the same key and time, if at least one of the Clients contains bool = true, I want to return a single client with bool = true otherwise return a single client with bool = false ... ie I want the output of above to be:
List (
Client(87658763,Some(1970-01-01T00:00:00Z),false),
Client(87658769,Some(1970-01-01T00:00:00Z),true)
)
What I have so far is the following code:
import java.time.Instant
case class Client(key: String, time: Option[Instant], bool: Boolean)
val l = List (
Client("87658763", Some(Instant.EPOCH), false),
Client("87658769", Some(Instant.EPOCH), false),
Client("87658769", Some(Instant.EPOCH), true)
)
l.groupBy(client => (client.key, client.time)).map {
case (_, v) if v.exists(_.bool) => v.head.copy(bool = true)
case (_, v) => v.head
}.toList
I am curious about efficiency and code style - this is the only way to solve this problem that I could come up with, but I wonder if there is a more efficient way to do this (I don't know much about what the Scala compiler does under the hood with things like groupBy and copy), or a more elegant way to do this.
I've not had to make elements distinct by more than one field before and this call will be made hundreds of times in my application (I am writing this as part of a Play! app) so need it to be as efficient as possible.