Tech Interview RoomStudy guides

Java 8

Java 8: Sort a list of employees by several fields. Show the evolution from anonymous Comparator to Comparator.comparing.

Intermediate · 2 min read · Lesson 4 of 10 in Java 8

Problem

Sort employees by department (alphabetical, null departments last), then salary (highest first), then name. Interviewers check that you know Java 8's Comparator combinators and common bugs in hand-written comparators.

The model (Java 8 style class, since records arrived later)

java
final class Emp {
    private final String name;
    private final String dept;
    private final double salary;

    Emp(String name, String dept, double salary) { this.name = name; this.dept = dept; this.salary = salary; }
    String getName() { return name; }
    String getDept() { return dept; }
    double getSalary() { return salary; }
    @Override public String toString() { return name + "(" + dept + ", " + (long) salary + ")"; }
}

Approach 1: Anonymous Comparator class (Java 7)

Verbose and easy to get wrong: every level must handle nulls and ties by hand.

java
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

class SortJava7 {
    static void sort(List<Emp> emps) {
        Collections.sort(emps, new Comparator<Emp>() {
            @Override
            public int compare(Emp a, Emp b) {
                if (a.getDept() == null && b.getDept() != null) return 1;
                if (a.getDept() != null && b.getDept() == null) return -1;
                if (a.getDept() != null) {
                    int byDept = a.getDept().compareTo(b.getDept());
                    if (byDept != 0) return byDept;
                }
                int bySalary = Double.compare(b.getSalary(), a.getSalary());   // descending
                if (bySalary != 0) return bySalary;
                return a.getName().compareTo(b.getName());
            }
        });
    }
}

Approach 2: The same logic as a lambda (Java 8)

Shorter, but still hand-written logic.

java
import java.util.List;

class SortLambda {
    static void sort(List<Emp> emps) {
        emps.sort((a, b) -> {
            if (a.getDept() == null || b.getDept() == null) {
                if (a.getDept() != b.getDept()) return a.getDept() == null ? 1 : -1;
            } else {
                int byDept = a.getDept().compareTo(b.getDept());
                if (byDept != 0) return byDept;
            }
            int bySalary = Double.compare(b.getSalary(), a.getSalary());
            return bySalary != 0 ? bySalary : a.getName().compareTo(b.getName());
        });
    }
}

Approach 3: Comparator combinators (Java 8, the idiomatic answer)

Each sort key is declared once; nullsLast, reversed and thenComparing remove the manual branching. comparingDouble avoids boxing.

java
import java.util.Comparator;
import java.util.List;

class SortCombinators {
    static final Comparator<Emp> ORDER =
        Comparator.comparing(Emp::getDept, Comparator.nullsLast(Comparator.naturalOrder()))
                  .thenComparing(Comparator.comparingDouble(Emp::getSalary).reversed())
                  .thenComparing(Emp::getName);

    static void sort(List<Emp> emps) { emps.sort(ORDER); }
}

Approach 4: Streams sorted (non-destructive)

When the source list must not change (it may be shared or unmodifiable), sort a copy in a pipeline.

java
import java.util.List;
import java.util.stream.Collectors;

class SortStreams {
    static List<Emp> sorted(List<Emp> emps) {
        return emps.stream().sorted(SortCombinators.ORDER).collect(Collectors.toList());
    }
}

Run all approaches

java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

class SortDemo {
    public static void main(String[] args) {
        List<Emp> base = Arrays.asList(
            new Emp("Zara", "Eng", 150), new Emp("Amit", "Eng", 200), new Emp("Bela", null, 300),
            new Emp("Chen", "Eng", 200), new Emp("Dev", "Admin", 100));
        List<Emp> a = new ArrayList<>(base), b = new ArrayList<>(base), c = new ArrayList<>(base);
        SortJava7.sort(a); SortLambda.sort(b); SortCombinators.sort(c);
        System.out.println(a);
        System.out.println(b);
        System.out.println(c);   // [Dev(Admin, 100), Amit(Eng, 200), Chen(Eng, 200), Zara(Eng, 150), Bela(null, 300)]
        System.out.println(SortStreams.sorted(base).equals(c));   // true
    }
}

Feasible → optimal

All four are O(n log n) (TimSort, stable). The difference is correctness risk and readability: Approach 3 is the professional answer. For very large lists where extracting a key is expensive (parsing, computing), precompute the keys once into a wrapper and sort the wrappers.

Follow-up questions interviewers ask

Try answering each one before you open it.

Why is `return a.getAge() - b.getAge();` a buggy comparator?

Integer subtraction can overflow: comparing Integer.MIN_VALUE with 1 gives a large positive result, so the order is wrong and can even violate the comparator contract (TimSort may then throw "Comparison method violates its general contract!"). Use Integer.compare(a, b) or Comparator.comparingInt. For doubles, Double.compare also handles NaN and -0.0 consistently.

Is Java's sort stable, and why does it matter?

List.sort and Collections.sort for objects use TimSort, which is stable: equal elements keep their relative order. That lets you sort by a secondary key first and then by the primary key, and it guarantees deterministic output for ties. Arrays.sort on primitives uses dual-pivot quicksort, which is not stable, but stability is meaningless for identical primitives.