TExcelTAD
Home › Java › Java Collections Sorting

Java Collections Sorting

Sorting is one of the most common things you'll do with data: names alphabetically, products by price, scores from highest to lowest. Java's standard library does the hard work — you just describe how two elements compare.

Sorting in natural order

Numbers, strings, dates and other built-in types have a natural order. Sort a list with Collections.sort(list) or list.sort(null), and an array with Arrays.sort(array):

java · try it yourself
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

class Main {
    public static void main(String[] args) {
        List<Integer> nums = new ArrayList<>(List.of(42, 7, 19, 3, 25));
        Collections.sort(nums);
        System.out.println(nums);

        List<String> words = new ArrayList<>(List.of("pear", "Apple", "fig", "banana"));
        Collections.sort(words);
        System.out.println(words);          // uppercase letters sort first

        int[] arr = {9, 4, 6, 1};
        Arrays.sort(arr);
        System.out.println(Arrays.toString(arr));

        Collections.reverse(nums);          // just reverses the current order
        System.out.println(nums);
    }
}
[3, 7, 19, 25, 42]
[Apple, banana, fig, pear]
[1, 4, 6, 9]
[42, 25, 19, 7, 3]

Note: Java's sort is stable: elements that compare as equal keep their original relative order. That makes multi-step sorting predictable.

Comparators

A Comparator<T> defines a custom order. Its method compare(a, b) returns a negative number if a comes first, zero if they're equal, and a positive number if b comes first. The Comparator class has factory methods so you rarely write compare by hand:

java · try it yourself
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

class Main {
    public static void main(String[] args) {
        List<String> words = new ArrayList<>(List.of("kiwi", "banana", "Fig", "apple", "cherry"));

        words.sort(Comparator.reverseOrder());
        System.out.println("Reverse:          " + words);

        words.sort(String.CASE_INSENSITIVE_ORDER);
        System.out.println("Ignore case:      " + words);

        words.sort(Comparator.comparing(String::length));
        System.out.println("By length:        " + words);

        words.sort(Comparator.comparing(String::length).thenComparing(Comparator.naturalOrder()));
        System.out.println("Length, then A-Z: " + words);
    }
}
Reverse:          [kiwi, cherry, banana, apple, Fig]
Ignore case:      [apple, banana, cherry, Fig, kiwi]
By length:        [Fig, kiwi, apple, banana, cherry]
Length, then A-Z: [Fig, kiwi, apple, banana, cherry]

Sorting your own objects

Comparator.comparing takes a function that extracts the sort key — usually a method reference to a getter or record accessor. Chain thenComparing for tie-breakers and reversed() to flip the order:

java · try it yourself
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

record Product(String name, String category, double price) { }

class Main {
    public static void main(String[] args) {
        List<Product> products = new ArrayList<>(List.of(
            new Product("Desk lamp", "home", 34.90),
            new Product("Mouse", "tech", 19.99),
            new Product("Kettle", "home", 24.50),
            new Product("Keyboard", "tech", 49.00),
            new Product("Mug", "home", 8.00)
        ));

        products.sort(Comparator.comparingDouble(Product::price));
        System.out.println("Cheapest first:");
        products.forEach(p -> System.out.printf("  %-10s %6.2f%n", p.name(), p.price()));

        products.sort(Comparator.comparing(Product::category)
                .thenComparing(Product::price, Comparator.reverseOrder()));
        System.out.println("By category, priciest first:");
        products.forEach(p -> System.out.printf("  %-5s %-10s %6.2f%n", p.category(), p.name(), p.price()));
    }
}
Cheapest first:
  Mug          8.00
  Mouse       19.99
  Kettle      24.50
  Desk lamp   34.90
  Keyboard    49.00
By category, priciest first:
  home  Desk lamp   34.90
  home  Kettle      24.50
  home  Mug          8.00
  tech  Keyboard    49.00
  tech  Mouse       19.99

Comparable: a natural order for your class

If a class has one obvious order, implement Comparable<T> and its compareTo method. Then Collections.sort, TreeSet and TreeMap can use it without a comparator:

java · try it yourself
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.TreeSet;

class Version implements Comparable<Version> {
    final int major, minor;

    Version(int major, int minor) {
        this.major = major;
        this.minor = minor;
    }

    @Override
    public int compareTo(Version other) {
        if (major != other.major) return Integer.compare(major, other.major);
        return Integer.compare(minor, other.minor);
    }

    @Override
    public String toString() {
        return major + "." + minor;
    }
}

class Main {
    public static void main(String[] args) {
        List<Version> versions = new ArrayList<>(List.of(
            new Version(2, 10), new Version(1, 4), new Version(2, 3), new Version(10, 0)));
        Collections.sort(versions);
        System.out.println(versions);
        System.out.println("Newest: " + Collections.max(versions));
        System.out.println(new TreeSet<>(versions).first());
    }
}
[1.4, 2.3, 2.10, 10.0]
Newest: 10.0
1.4

Notice that comparing as numbers gives the correct order 2.3 < 2.10 < 10.0, which comparing the strings would get wrong.

Tip: Use Integer.compare(a, b) rather than a - b in compareTo. Subtraction can overflow for large values and produce the wrong sign.

Comparable Comparator
Where implemented by the class itself separate object/lambda
Method compareTo(other) compare(a, b)
How many one natural order as many orders as you like
Used by Collections.sort(list), TreeSet list.sort(cmp), new TreeSet<>(cmp)

Test yourself

What should compare(a, b) return when a should come before b?

  1. A positive number
  2. Zero
  3. A negative number
  4. true

How do you sort a list of people by age, then by name?

  1. Comparator.comparing(Person::age).thenComparing(Person::name)
  2. Collections.sort(age, name)
  3. list.sortBy(age, name)
  4. Comparator.thenComparing(Person::age, Person::name)

Which interface gives a class its natural ordering?

  1. Comparator
  2. Comparable
  3. Sortable
  4. Iterable