https://kotlinlang.org logo
#codereview
Title
# codereview
v

Vivek Modi

05/17/2022, 9:31 AM
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

Klitos Kyriacou

05/17/2022, 9:46 AM
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

Vivek Modi

05/17/2022, 9:48 AM
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

Robert Williams

05/17/2022, 9:52 AM
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

Klitos Kyriacou

05/17/2022, 9:56 AM
@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

Vivek Modi

05/17/2022, 10:12 AM
Ok now I clearly understand that. Thank you so much @Klitos Kyriacou
3 Views