Do you think IIT Guwahati certified course can help you in your career?
No
Introduction
A tree is a well-known data structure used to organise and represent hierarchical data. It is a collection of objects, known as nodes, linked together in a non-linear manner. A red-black tree is a self-balancing binary search tree in which every path from a node to any of its descendent null nodes should have the same number of black nodes.
A TreeMap is a red-black tree based NavigableMap implementation. The Navigable Map Interface is a member of the Java Collections framework and an extension of the SortedMap class that provides convenient navigation methods to traverse a map. TreeMap also implements the Map interface and the AbstractMap class.
Declaration
public class TreeMap<K,V> extends AbstractMap<K,V> implements NavigableMap<K,V>, Cloneable, Serializable
Initialization
TreeMap<K, V> objectName = new TreeMap<K, V>();
K - Key object type V - Value object type
Hierarchy of TreeMap in Map Interface
Features of TreeMap in Java
TreeMap contains key-value mappings sorted in the natural ordering of their keys by default. The mappings can also be sorted using a comparator at map creation time.
TreeMap implementation is not synchronised, i.e. if multiple threads access a Map concurrently where at least one thread makes structural modifications, it must be synchronised externally.
TreeMap allows the use of null values but not null keys.
Its implementation has a time cost of log(n) on all insertion, deletion and access operations.
It does not support the Entry.setValue method. All entry pairs returned by methods in this class represent the mappings at the time they were produced.
Internal Working of Java TreeMap
Data Structure: Implemented as a Red-Black Tree (self-balancing binary search tree).
Key-Value Pairs: Stores data in key-value pairs, where keys are unique.
Ordering: Keys are sorted in their natural order or by a custom comparator.
NavigableMap Interface: Implements NavigableMap, allowing operations like ceiling(), floor(), etc.
Complexity: Most operations like put(), remove(), get() have O(log n) time complexity.
Red-Black Tree Properties: Ensures balanced tree structure for efficient search, insertion, and deletion.
Constructors TreeMap in Java
1. TreeMap()
It constructs a new, empty treemap with the natural ordering of its keys.
TreeMap<Integer, String> tree_map = new TreeMap<Integer, String>();
2. TreeMap(Comparator<? super K> comparator)
It constructs a new, empty treemap, whose keys are ordered according to the given comparator.
import java.util.*;
import java.util.concurrent.*;
// Comparator implementation
class Sort_keys implements Comparator<K>
{
// Comparator code
}
// Main class
public class Main
{
public static void main(String[] args)
{
TreeMap<K, V> tree_map = new TreeMap<K, V>(new Sort_keys());
}
}
3. TreeMap(Map<? extends K,? extends V> m)
It constructs a new tree map containing the same mappings as the given map, with the natural ordering of its keys.
import java.util.*;
public class Main
{
public static void main(String[] args)
{
Map<Integer, String> hash_map = new HashMap<Integer, String>();
// code to perform operations on hash_map
TreeMap<Integer, String> tree_map = new TreeMap<Integer, String>(hash_map);
}
}
4. TreeMap(SortedMap<K,? extends V> m)
It constructs a new tree map containing the same mappings and ordering as the specified sorted map.
import java.util.*;
import java.util.concurrent.*;
public class Main
{
public static void main(String[] args)
{
SortedMap<Integer, String> sorted_map = new ConcurrentSkipListMap<Integer, String>();
// code to perform operations on sorted_map
TreeMap<Integer, String> tree_map = new TreeMap<Integer, String>(sorted_map);
}
}
Methods of Java TreeMap Class
Method
Type
Description
clear()
void
It removes all the mappings from a specified map.
clone()
Object
It returns a shallow copy of the identity hash map but does not clone its key-value pairs.
containsKey(Object Key)
boolean
It returns true if the given object is a key in the map.
containsValue(Object value)
It returns true if the given object is mapped to one or more keys in the map.
entrySet()
Set<Map.Entry<K, V>>
It returns a set-view of all the mappings present in the map.
forEach(action)
void
It performs a given action for each key-value pair.
get(Object key)
V
It returns the value of the given key if it is present in the map else, it returns null.
keySet()
KeySetView<K, V>
It returns a set-view of the keys present in the map
put(K key, V value)
V
It adds a key-value pair to the identity hash map. If the key already exists, then its value is updated.
putAll(Map m)
void
It copies all the key-value mappings of a given map and replaces the original content of the map
remove(Object key)
V
It removes the mapping for a given key if it is present in the map.
replace(K key,V value)
V
It replaces the value of a given key only if it is currently mapped to some value.
replace(K key, V oldValue, V newValue)
boolean
It replaces the value of a given key only if it is currently mapped to the specified value.
replaceAll(function)
void
It replaces the values of every key with a value generated by a given function.
size()
int
It returns the number of key-value pairs in the identity hash map.
values()
Collection<V>
It returns a collection view of the values present in the map.
ceilingEntry(K key)
Map.Entry<K, V>
It returns the mapping associated with the least key greater than or equal to the given key or null if absent.
ceilingKey(K key)
K
It returns the least key greater than or equal to the given key or null if absent.
comparator()
Comparator<? super K>
It returns the comparator used to order the keys in the TreeMap.
descendingKeySey()
NavigableSet<K>
It returns a reverse order of the NavigableSet view of keys in the map.
navigableKetSet()
NavigableSet<K>
It returns a NavigableSet view of all the keys in the map.
descendingMap()
NavigableMap<K,V>
It returns a reverse order view of all mappings in the map.
firstEntry()
Map.Entry<K, V>
It returns the mapping associated with the least key in the map.
firstKey()
K
It returns the first key in the map.
floorEntry(K key)
Map.Entry<K, V>
It returns the mapping associated with the greatest key less than or equal to the given key or null if absent.
floorKey(K key)
K
It returns the greatest key less than or equal to the given key or null if absent.
headMap(K toKey)
SortedMap<K, V>
It returns a portion of the map whose keys are strictly less than the given key, excluding the key itself.
higherEntry(K key)
Map.Entry<K, V>
It returns the mapping associated with the least key strictly greater than the given key or null if absent.
higherKey(K key)
K
It returns the least key strictly greater than the given key or null if absent.
lastEntry()
Map.Entry<K, V>
It returns the mapping associated with the greatest key in the map.
lastKey()
K
It returns the last key in the map.
lowerEntry<K key)
Map.Entry<K, V>
It returns the mapping associated with the greatest key strictly less than the given key or null if absent.
lowerkey(K key)
K
It returns the greatest key strictly less than the given key or null if absent.
pollFirstEntry()
Map.Entry<K, V>
It removes and returns the mapping associated with the least key in the map, or null is absent.
pollLastEntry()
It removes and returns the mapping associated with the greatest key in the map, or null is absent.
subMap(K keyA, K keyB)
SortedMap<K, V>
It returns the map portion containing mappings whose keys range from keyA to keyB, including keyA but excluding keyB.
tailMap(K keyA)
It returns the mappings of keys greater than keyA and keyA itself.
// Accessing elements System.out.println("TreeMap of country-capital: " + country.entrySet()); System.out.println("\nList of keys (Country): " + country.keySet()); System.out.println("List of values (Capitals): " + country.values()); System.out.println("\nThe capital of France is :" + country.get("France")); System.out.println();
// Replacing elements country.replace("France","Paris"); System.out.println("Correcting the capital the of France to " + country.replace("France","Paris")); System.out.println(country); System.out.println("\nAbbreviating the names of all capitals."); country.replaceAll((key , oldValue) -> oldValue.substring(0, 3)); System.out.println(country + "\n");
//Removing elements System.out.println("Removing Australia: " + country.remove("Australia")); System.out.println(country); } }
You can also try this code with Online Java Compiler
TreeMap of country-capital: [Australia=Canberra, France=London, Germany=Berlin, India=New Delhi]
List of keys Country): [Australia, France, Germany, India]
List of values (Capitals): [Canberra, London, Berlin, New Delhi]
The capital of France is :London
Correcting the capital the of France to Paris
{Australia=Canberra, France=Paris, Germany=Berlin, India=New Delhi}
Abbreviating the names of all capitals.
{Australia=Can, France=Par, Germany=Ber, India=New}
Removing Australia: Can
{France=Par, Germany=Ber, India=New}
Navigation Operations on TreeMap
Obtain first and last mappings or keys.
Obtain highest and lowest mappings or keys.
Use of ceiling and floor methods.
Use of pollFirstEntry() and pollLastEntry() methods.
Java
Java
import java.util.TreeMap;
public class Main { public static void main(String[] args) { TreeMap<String, String> country = new TreeMap<>();
// poll first and last entry System.out.println("Poll first entry: " + country.pollFirstEntry()); System.out.println("Poll last entry: " + country.pollLastEntry()); System.out.println(country); System.out.println(); } }
You can also try this code with Online Java Compiler
Sorted Order: Automatically maintains keys in natural or custom order, making it ideal for applications requiring sorted data.
Efficient Search: Red-Black Tree structure offers O(log n) time complexity for get(), put(), and remove().
NavigableMap Interface: Implements the NavigableMap interface, supporting efficient navigation methods like ceiling(), floor(), higher(), and lower().
No Duplicates: Ensures uniqueness of keys, providing a reliable map structure where duplicate keys are not allowed.
Range Views: Allows operations like subMap(), headMap(), and tailMap() for efficient range querying.
Thread Safety: While not synchronized, individual operations on TreeMap are thread-safe when accessed by a single thread.
Flexible Sorting: Can use a custom comparator for sorting keys, offering flexibility for complex ordering.
Disadvantages of TreeMap in Java
Slower than HashMap: Due to sorting and balancing, TreeMap operations (like put() and get()) are slower (O(log n)) compared to HashMap (O(1) average).
No Null Keys: TreeMap does not allow null keys, unlike HashMap, which can store null values.
Memory Overhead: The Red-Black Tree structure requires extra memory for tree nodes and balancing information.
Not Synchronized: By default, TreeMap is not thread-safe for concurrent modifications. External synchronization is needed in multi-threaded environments.
Comparator Dependency: If the comparator is not provided, the natural ordering of keys must be consistent, which might not always be desirable.
Performance with Large Data: Performance may degrade with very large datasets, as balancing the tree requires more time compared to other structures.
Frequently Asked Questions
What is the SortedMap interface, and how is it different from TreeMap?
The SortedMap interface provides a natural ordering of its keys for easy traversal. Its parent interface is the Map interface, and its subinterface is the NavigableMap.
SortedMap cannot be used to create objects as it is an interface. The implementation of the sortedMap is the TreeMap using which objects can be created. While the SortedMap restricts the use of null keys and null values, the TreeMap imposes restrictions only on the use of null keys.
Is TreeMap ordered in Java?
Yes, TreeMap is ordered. It stores keys in their natural order or according to a custom comparator provided at the time of creation.
Does TreeMap allow null keys?
No, TreeMap does not allow null keys. It throws a NullPointerException if you attempt to insert a null key.
What is the difference between TreeMap and TreeSet in Java?
TreeMap stores key-value pairs, while TreeSet stores only unique keys. Both use a Red-Black Tree, but TreeMap maps keys to values, whereas TreeSet only maintains unique keys.
Can TreeMap have duplicate values?
Yes, TreeMap allows duplicate values but not duplicate keys. The values can be repeated, but each key must be unique.
Conclusion
TreeMaps are special and extremely useful. The mappings they store can be arranged in the ascending order of its keys or by using the comparator as discussed. Since the mappings are already sorted, they quickly access its key-value pairs. This blog explains the TreeMap class in detail, along with its features and constructors. It also lists out the various functions and methods provided by this class to work with key-value mappings.