Start learning free

LESSON 267 OF 677 · PAIRS, SORTING & BUILT-INS

Custom Sorting in Kotlin

Lesson

TL ; DR:

To sort by your own rule, pass a lambda. It is a small function in braces. It says what to sort each item by.


val nums = mutableListOf(25, 13, 5, 41, 33)

val byLastDigit = nums.sortedWith(compareBy({ it % 10 }, { it }))
// [41, 13, 33, 5, 25]

val scores = mutableListOf(70, 95, 82)

val highFirst = scores.sortedByDescending { it }
// [95, 82, 70]


Full lesson:

You met sorted() in the Shopping Cart project. It sorts from small to large, or from A to Z. Sometimes you need another order. The shortest word may have to come first, or the highest score.

Then pass a lambda. A lambda is a small function in braces. It has no name. In { it.length }, it is the one item the lambda gets. The lambda returns that item's length.

  • The call sortedBy { it.length } sorts by what the lambda returns, from small to large.
  • The call sortedByDescending { it } sorts from large to small.
  • The call sortedWith(compareBy({ it % 10 }, { it })) uses two rules. It sorts numbers by their last digit, then from small to large. The second lambda only sorts items that tie on the first.

The sorted... functions make a new list. The old list stays as it was.

On a mutableListOf list, sortBy and sortWith sort the list itself instead.


Your task

A pet shop sells toys. Their prices are in prices. Make a list named highFirst with the prices from high to low.

The shop's pets are in names. Make a list named byLastLetter with the names sorted by their last letter, in alphabetical order. Names with the same last letter go from A to Z.

The code already prints both, one item per line.

Expected output:

30
12
8
5
Bella
Luna
Bo
Coco
Max
Rex
STEP 1 OF 2
    Ctrl + Enter to check