Say I have objects that look like this
data class Test(val id: Int, val timeStamp: Long)
So a data set might look like
val data = listOf(
Test(1, 100),
Test(1, 150),
Test(2, 50),
Test(2, 150),
Test(2, 300),
)
I want to be able to filter the list so that I get the latest timestamp of each ID, so my expected output is
data = listOf(
Test(1, 150),
Test(2, 300),
)
Was looking at using groupBy, but was not quite sure where to go from there. The list given is sorted ascending.
CodePudding user response:
You can do it using groupBy
and maxBy
like this:
data.groupBy { it.id }.values.map { it.maxBy(Test::timeStamp) }
In case of your data is sorted, you can use last
instead of maxBy
:
data.groupBy { it.id }.values.map { it.last() }
Another way is associateBy
, it automatically gets the last element for you:
data.associateBy { it.id }.values.toList()
CodePudding user response:
I think this is one way. I couldn't find any way combining grouping and maxBy. So created unique value set. Then loop and filter the main list with id and get max of that filtered list and add to result.
val result = arrayListOf<Test>()
data.map { it.id }.toSet().forEach {id->
data.filter {
it.id == id
}.maxBy {
it.timeStamp
}?.let {
result.add(it)
}
}