Start learning free

LESSON 263 OF 671 · RECORDS, SORTING & BUILT-INS

Custom Sorting in Java

Lesson

TL ; DR:

To sort by your own rule, give sort a lambda. It gets two items, a and b. A negative result puts a first.


List<Integer> nums = new ArrayList<>(List.of(25, 13, 5, 41, 33));

nums.sort((a, b) -> {
    if (a % 10 != b % 10) {
        return a % 10 - b % 10;
    }

    return a - b;
});
// [41, 13, 33, 5, 25]

List<Integer> scores = new ArrayList<>(List.of(70, 95, 82));

scores.sort((a, b) -> b - a);
// [95, 82, 70]


Full lesson:

You met Collections.sort 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.

For that, give the list's sort method a lambda. A lambda is a small function written right where you need it. It has no name. The lambda (a, b) -> a - b gets two values, a and b, and returns a - b.

The sort method calls it on two items at a time. The result says which one goes first.

  • A negative number puts a first.
  • A positive number puts b first.
  • Zero means they are equal.

Some rules you will use often:

  • Low to high: (a, b) -> a - b.
  • High to low: (a, b) -> b - a.
  • Shortest first: (a, b) -> a.length() - b.length().

For plain numbers or text, list.sort(Comparator.reverseOrder()) also sorts from high to low.

For two rules, the lambda needs a body in braces. Check the first rule. Use the second one only on a tie, as the if above does.

Above, the first rule compares the last digits, a % 10 and b % 10. Numbers with the same last digit then go from small to large.

You met compareTo in Top Scorer. It gives a negative number when a comes first from A to Z.

The sort method changes the list itself. To keep the original, sort a copy made with new ArrayList<>(words).


Your task

A pet shop sells toys. Their prices are in prices. Sort prices from high to low.

The shop's pets are in names. Sort names 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 4
    Ctrl + Enter to check