Start learning free

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

Custom Sorting in Scala

Lesson

TL ; DR:

To sort by your own rule, give sortBy a small function. It says what to sort each item by.


val nums = scala.collection.mutable.ArrayBuffer(25, 13, 5, 41, 33)

val byLastDigit = nums.sortBy(n => (n % 10, n))
// ArrayBuffer(41, 13, 33, 5, 25)

val scores = scala.collection.mutable.ArrayBuffer(70, 95, 82)

val highFirst = scores.sortBy(s => -s)
// ArrayBuffer(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 use sortBy with a small function. The function w => w.length is written in one line. It has no name. It gets one value, w, and returns its length. The sortBy method sorts the items by what the function returns.

  • The call sortBy(w => w.length) sorts by length.
  • The call sortBy(n => (n % 10, n)) uses two rules. The function returns a tuple: the last digit, then the number. Tuples are compared item by item. So numbers with the same last digit go from small to large.
  • The call sortBy(s => -s) sorts numbers from high to low. The biggest number has the smallest -s.

The sortBy method makes a new ArrayBuffer. The old one stays as it was.

To sort an ArrayBuffer itself, use sortInPlaceBy instead.


Your task

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

The shop's pets are in names. Make an ArrayBuffer 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