Search code examples
sortingkotlincomparable

Sorting and grouping in kotlin


I have a list of objects in the kotlin and I want to sort them by number and then by string. Is there a way to do this? I've gone through hundreds of articles, but nothing works anywhere.

myList.sortedWith(compareBy<Item> {it.name.id }.thenBy{it.name.secondname}) This code do not works.

Of course myList is a type of Item.

Greetings

@EDIT

But what if I have 10 same ids? The code will not reach the .thenBy check. Is there a possibility to check a whole pair of fields?


Solution

  • myList.sortedWith(compareBy<Item> {it.name.id }.thenBy{it.name.secondname}) returns a sorted copy of the list, but it doesn't modify the original one.

    If you want the original list to be modified, you can either use sortWith instead of sortedWith:

    myList.sortWith(compareBy<Item> { it.name.id }.thenBy { it.name.secondname })
    

    Or reassign myList variable:

    myList = myList.sortedWith(compareBy<Item> { it.name.id }.thenBy { it.name.secondname })