Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Disclosure: My content contains affiliate links.

43,236 questions

56,139 answers

573 users

How to sort a list of data classes by multiple columns in Kotlin

1 Answer

0 votes
data class Item(val a: Int, val b: Int, val label: String)

fun sortData(items: List<Item>): List<Item> =
    items.sortedWith(compareBy<Item> { it.a }.thenBy { it.b })

fun printData(items: List<Item>) =
    items.forEach { println("(${it.a}, ${it.b}, ${it.label})") }

fun findByLabel(items: List<Item>, label: String): Item? =
    items.find { it.label == label }

fun filterByA(items: List<Item>, value: Int): List<Item> =
    items.filter { it.a == value }

fun main() {
    val data = listOf(
        Item(7, 2, "python"),
        Item(8, 3, "c"),
        Item(3, 5, "c++"),
        Item(4, 1, "c#"),
        Item(3, 2, "java"),
        Item(7, 1, "go"),
        Item(1, 2, "rust")
    )

    val sorted = sortData(data)
    println("Sorted data:")
    printData(sorted)

    println("\nSearching for 'java':")
    findByLabel(sorted, "java")?.let { println(it) }

    println("\nFiltering items where a == 7:")
    val filtered = filterByA(sorted, 7)
    printData(filtered)
}




/*
run:

Sorted data:
(1, 2, rust)
(3, 2, java)
(3, 5, c++)
(4, 1, c#)
(7, 1, go)
(7, 2, python)
(8, 3, c)

Searching for 'java':
Item(a=3, b=2, label=java)

Filtering items where a == 7:
(7, 1, go)
(7, 2, python)

*/

 



answered Jan 29 by avibootz

Related questions

...