Hello again! This lesson's topic is Sorted Maps. Similar to other map structures, Sorted Maps store key-value pairs but in an ordered manner. Learning about Sorted Maps enriches our set of tools for organized and efficient data manipulation. Today's goal is to work with Sorted Maps using Java's TreeMap class.
In Java, we differentiate between regular maps like HashMap and Sorted Maps. Comparing HashMap to TreeMap is akin to comparing a messy bookshelf to a well-organized library — the latter maintains order. HashMap does not guarantee any order of keys, whereas TreeMap sorts the keys in natural order (if they implement the Comparable interface) or according to a specified comparator.
The TreeMap class is part of the Java Collections Framework and provides a Red-Black tree-based implementation of the NavigableMap interface. This ensures that the map is always sorted according to the natural ordering of its keys or by a custom comparator.
To create a TreeMap object, you can either use the default constructor or initialize it with a map. The keys used in a TreeMap must be immutable and comparable. For instance:
The output will be:
In this example, the keys are sorted in alphabetical order. This means that "apple" comes first because 'a' is earlier in the alphabet than 'b' from "banana", 'o' from "orange", and 'p' from "pear". Conversely, "pear" is the greatest key because 'p' has a higher ASCII value than 'a', 'b', and 'o'.
A TreeMap object boasts several useful methods. Here are some crucial ones:
treeMap.ceilingKey(key): This returns the least key greater than or equal to the specified key, ornullif there is no such key.treeMap.floorKey(key): This returns the greatest key less than or equal to the specified key, ornullif there is no such key.treeMap.remove(key): This removes the entry for the specified key if it is present and returns its associated value.treeMap.get(key): This returns the value to which the specified key is mapped, ornullif the map contains no mapping for the key.treeMap.lastEntry(): This returns the key-value pair corresponding to the greatest key, ornullif the map is empty.
Consider the following Java code, which incorporates these methods:
