Home > Software design >  Best way to find multiple items in single list kotlin
Best way to find multiple items in single list kotlin

Time:05-17

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 efficient, memory management or anything which is good.

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

"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"
        }]

CodePudding user response:

Your original code performs 3 iterations over list. You can do it using single iteration - first you group events by status then fetch (first/last)event from that map according to the status:

val eventsGroupped = events?.groupBy { it.status }  // Map<String, List<Event>>

val completeEvent = eventsGroupped?.get("complete")?.lastOrNull()
val activeEvent = eventsGroupped?.get("active")?.firstOrNull()
val futureEvent = eventsGroupped?.get("future")?.firstOrNull()
  • Related