Java
Beginner
1 min read
TreeMap and Sorting Collections
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);
}
}