Vivek Modi
05/17/2022, 9:31 AMval completeEvent = events?.lastOrNull { events -> events.status == "complete" }
val activeEvent = events?.find { events -> events.status == "active" }
val futureEvent = events?.firstOrNull { events -> events.status == "future" }
ApiResponse
"Events": [{
"title": "Test 1",
"status": "complete"
}, {
"title": "Test 2",
"status": "complete"
}, {
"title": "Test 3",
"status": "complete",
}, {
"title": "Test 4",
"status": "complete"
}, {
"title": "Test 5",
"status": "complete"
}, {
"title": "Test 6",
"status": "active"
}, {
"title": "Test 7",
"status": "future"
}, {
"title": "Test 8",
"status": "future"
}]
Klitos Kyriacou
05/17/2022, 9:46 AMfirstOrNull
instead of find
as its name shows the intent more clearly).Vivek Modi
05/17/2022, 9:48 AMval eventsGroup = events?.groupBy { it.status }
val completeEvent = eventsGroup?.get(COMPLETE_EVENT)?.lastOrNull()
val activeEvent = eventsGroup?.get(ACTIVE_EVENT)?.firstOrNull()
val futureEvent = eventsGroup?.get(FUTURE_EVENT)?.firstOrNull()
Robert Williams
05/17/2022, 9:52 AM//Anywhere in the file outside the class
private fun Event.isComplete() = status == "complete"
...
val completeEvent = events?.lastOrNull(::isComplete)
Klitos Kyriacou
05/17/2022, 9:56 AMeventsGroup
, then using it at this point might be a good idea. But if you are only creating eventsGroup
just for this purpose, then it doesn't look at all efficient.
Your original code will iterate backwards to find the last complete event, and then stop as soon as it finds it. It will iterate from the beginning to find the first active event and stop as soon as it finds it. The groupBy
method will iterate the whole list regardless. It will also create potentially large lists which you don't need and throw away as you're only interested in 1 element.Vivek Modi
05/17/2022, 10:12 AM