SyntaxStudy
Sign Up
Java TreeMap and Sorting Collections
Java Beginner 1 min read

TreeMap and Sorting Collections

TreeMap is a sorted Map implementation backed by a Red-Black tree. It keeps its keys in natural ascending order (or according to a provided Comparator), which makes it useful when you need a map whose keys are always sorted. All basic operations — get, put, remove — run in O(log n) time. TreeMap also provides useful navigation methods like firstKey(), lastKey(), headMap(), tailMap(), and subMap(). The Collections utility class provides powerful static methods for working with any List: Collections.sort() sorts a list using natural ordering or a Comparator, Collections.reverse() reverses the order, Collections.shuffle() randomises the order, and Collections.min()/max() find the extreme values. These methods work with any collection that implements the appropriate interfaces. For sorting, Java provides two approaches: make your object implement Comparable (defining its natural ordering via compareTo()), or pass a Comparator to the sort method. Modern Java encourages using lambda expressions or Comparator.comparing() factory methods to build comparators concisely, making it easy to sort by multiple fields in a readable way.
Example
import java.util.*;

public class TreeMapSortDemo {
    public static void main(String[] args) {
        // --- TreeMap (sorted by key) ---
        TreeMap<String, Integer> population = new TreeMap<>();
        population.put("Tokyo",    14000000);
        population.put("New York",  8000000);
        population.put("London",    9000000);
        population.put("Berlin",    3700000);

        System.out.println("Sorted map: " + population);
        System.out.println("First key:  " + population.firstKey());
        System.out.println("Last key:   " + population.lastKey());
        System.out.println("Head map (< London): " + population.headMap("London"));

        // --- Sorting a List with Comparator ---
        List<String> names = new ArrayList<>(Arrays.asList(
            "Charlie", "Alice", "Bob", "Dave"
        ));

        Collections.sort(names); // natural order
        System.out.println("\nNatural sort: " + names);

        names.sort(Comparator.comparingInt(String::length)
                             .thenComparing(Comparator.naturalOrder()));
        System.out.println("By length, then alpha: " + names);

        // --- Collections utilities ---
        System.out.println("Min: " + Collections.min(names));
        System.out.println("Max: " + Collections.max(names));
        Collections.reverse(names);
        System.out.println("Reversed: " + names);
    }
}