Good Morning guys, What is the best approach to find three items in single list. I tried some code a...
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"
		}]
g
not very efficient way, though fast to write and readablke. Don’t think that there is anything better in stdlib, probably old good imperative forEach and update variables would be more efficient of course (and I probably would use it instead of 3 separate search)
but I think now, actually 1 single forEach wouldn’t be more efficient in all cases, because you also have
lastOrNull
so there is always cases when 3 separate first/last will be actually faster than a single forEach (because it always iterate all the items) So I think it’s a legit solution for your particular example
🙌 2
v
thank you so much. I understand clearly
j
lastOrNull
iterates backwards, so it doesn’t “always iterate all the items”
g
This is exactly what I said, that solution with forEach which requires find not only first, but also some "last" item, have to iterate through the whole list, which is not always the case of separate searches Though you pay the price of N iterators per N searched items
v
Yeah got it
thank you so much guys