test
test

Reputation: 467

Kotlin divide the list into lists

I have list of objects and in object I have parametr productId and I want to for one big list get few list group by productId I try do this :

   val listOne = arrayListOf<TicketDisplay>()
                val listTwo = arrayListOf<TicketDisplay>()
                ticketDisplayList.forEach { ticket ->
                    when (ticket.zoneId) {
                        1.toLong() -> {
                            listOne.add(ticket)
                        }
                        3.toLong() -> {
                            listTwo.add(ticket)

                        }
                    }
                }

Upvotes: 1

Views: 86

Answers (1)

Giorgio Antonioli
Giorgio Antonioli

Reputation: 16214

You can do it using groupBy:

val groups = ticketDisplayList.groupBy { ticket -> ticket.zoneId }
// The list of the tickets with zoneId 1.
val listOne = groups[1]
// The list of the tickets with zoneId 3.
val listTwo = groups[3]

Upvotes: 3

Related Questions