0% completed
The TreeMap
class is a part of the Java Collections Framework and provides a map implementation that stores key-value pairs in a sorted order. It implements the NavigableMap
and SortedMap
interfaces, which means that the keys in a TreeMap are maintained either in their natural order (if the keys implement the Comparable
interface) or in an order determined by a custom comparator provided at the time of creation.
TreeMap is particularly useful when you need to perform range queries or iterate over keys in a sorted manner. However, note that TreeMap does not allow null keys (although null values are permitted) and its operations typically have logarithmic time complexity due to the underlying red-black tree data structure.
firstKey()
, lastKey()
, ceilingKey()
, and floorKey()
for navigating the sorted keys.TreeMap<KeyType, ValueType> treeMap = new TreeMap<KeyType, ValueType>();
KeyType
and values of type ValueType
, sorting the keys by their natural order.TreeMap<KeyType, ValueType> treeMap = new TreeMap<KeyType, ValueType>(customComparator);
customComparator
is an instance of a class that implements Comparator<KeyType>
.In this example, we create a TreeMap of String keys and Integer values. We add several key-value pairs, and then we display the map. The keys will be automatically sorted in their natural (alphabetical) order.
Example Explanation:
TreeMap<String, Integer>
named studentGrades
is created.put()
method adds entries, such as ("Charlie", 78), ("Alice", 88), ("David", 92), and ("Bob", 90).This example demonstrates how to use a custom comparator to sort keys in descending order. We create a TreeMap of Integer keys and String values. The custom comparator will reverse the natural ordering, so the largest key appears first.
Example Explanation:
DescendingComparator
class implements Comparator<Integer>
and overrides compare()
to sort integers in descending order.scoreBoard
is instantiated with the custom comparator, ensuring that keys (scores) are sorted in descending order.put()
method adds entries such as (50, "Player A"), (75, "Player B"), (60, "Player C"), and (85, "Player D").Understanding TreeMap is crucial for applications that require sorted data, efficient range queries, and navigation through key-value pairs in a defined order.
.....
.....
.....