Sorting: Comparable and Comparator

Sorting a list

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;

public class Main {
    public static void main(String[] args) {
        ArrayList<Integer> nums = new ArrayList<>(Arrays.asList(42, 7, 19, 3));
        Collections.sort(nums);
        System.out.println(nums);
        Collections.reverse(nums);
        System.out.println(nums);
        System.out.println("Max: " + Collections.max(nums) + ", Min: " + Collections.min(nums));
    }
}

Output

[3, 7, 19, 42]
[42, 19, 7, 3]
Max: 42, Min: 3

Sorting your own objects: Comparable

Java knows how to sort numbers and Strings, but not your Student objects. Implement Comparable and write compareTo to give them a natural order. Return a negative number if this comes first, positive if other does, 0 if equal:

import java.util.ArrayList;
import java.util.Collections;

class Student implements Comparable<Student> {
    String name;
    int marks;

    Student(String name, int marks) {
        this.name = name;
        this.marks = marks;
    }

    public int compareTo(Student other) {
        return Integer.compare(this.marks, other.marks);
    }

    public String toString() {
        return name + "(" + marks + ")";
    }
}

public class Main {
    public static void main(String[] args) {
        ArrayList<Student> list = new ArrayList<>();
        list.add(new Student("Asha", 91));
        list.add(new Student("Ravi", 78));
        list.add(new Student("Meera", 85));
        Collections.sort(list);
        System.out.println(list);
    }
}

Output

[Ravi(78), Meera(85), Asha(91)]

Other orders: Comparator

A Comparator is a separate “sorting rule”. You can make as many as you like. The short -> form is a lambda, which you'll study properly in the next module:

import java.util.ArrayList;
import java.util.Comparator;

class Student {
    String name;
    int marks;
    Student(String name, int marks) { this.name = name; this.marks = marks; }
    public String toString() { return name + "(" + marks + ")"; }
}

public class Main {
    public static void main(String[] args) {
        ArrayList<Student> list = new ArrayList<>();
        list.add(new Student("Ravi", 78));
        list.add(new Student("Asha", 91));
        list.add(new Student("Meera", 85));

        list.sort(Comparator.comparing(s -> s.name));
        System.out.println("By name: " + list);

        list.sort((a, b) -> b.marks - a.marks);
        System.out.println("Top marks first: " + list);
    }
}

Output

By name: [Asha(91), Meera(85), Ravi(78)]
Top marks first: [Asha(91), Meera(85), Ravi(78)]

Remember: Comparable = the one natural order, written inside the class. Comparator = any extra order, written outside.

HOME LABS COMMUNITY DASHBOARD