Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Best way to find multiple items in single list kotlin

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading