Good Morning guys, What is the best approach to fi...
# codereview
v
Good Morning guys, What is the best approach to find three items in single list. I tried some code and working fine. I want to know is there any better approach for this
Copy code
val completeEvent = events?.lastOrNull { events -> events.status == "complete" }
val activeEvent = events?.find { events -> events.status == "active" }
val futureEvent = events?.firstOrNull { events -> events.status == "future" }
ApiResponse
Copy code
"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"
		}]
k
I think it looks fine as it is (though I would use
firstOrNull
instead of
find
as its name shows the intent more clearly).
v
Hey @Klitos Kyriacou I tried some code, which one is more better.
Copy code
val 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()
r
Another option to clean things up is extension funs:
Copy code
//Anywhere in the file outside the class
private fun Event.isComplete() = status == "complete"
...
val completeEvent = events?.lastOrNull(::isComplete)
👍 1
k
@Vivek Modi It depends. If you are planning to proceed and do something additional with
eventsGroup
, 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.
👍 1
v
Ok now I clearly understand that. Thank you so much @Klitos Kyriacou