Java.util.TreeMap implements SortedMap interface and provides an efficient way to storing key-value pairs in sorted order. TreeMap implements the NavigableMap interface and extends AbstractMap class.
Points to Remember
- TreeMap uses data structure as a red-black tree.
- TreeMap contains values based on the key.
- TreeMap contains only unique elements.
- TreeMap cannot have a null key but can have multiple null values.
- TreeMap is not synchronized.
- TreeMap maintains an ascending order.
TreeMap Declaration
public class TreeMap extends AbstractMap implements NavigableMap, Serializable
,Cloneable
- K: Represent as key in Map
- V: Represent as value with respect to K.
See Also:
- Java: How HashMap works?
- Java: HashTable Class Methods and Examples
- Java: HashMap Class Methods and Examples
- Java: Difference between HashMap and Hashtable
What is the difference between HashMap and TreeMap?
HashMap | TreeMap |
HashMap can contain one null key. | TreeMap cannot contain any null key. |
HashMap maintains no order. | TreeMap maintains an ascending order. |
Constructors of TreeMap
Constructor | Description |
TreeMap() | This constructor uses to create an empty treemap that will be sorted using the natural order of its key. |
TreeMap(Comparator comparator) | This constructor uses to an empty tree-based map that will be sorted using the comparator comp. |
TreeMap(Map m) | It is used to initialize a treemap with the entries from m, which will be sorted using the natural order of the keys. |
TreeMap(SortedMap m) | This constructor uses to initialize a treemap with the entries from the SortedMap sm, which will be sorted in the same order as sm. |
Methods of TreeMap
Method | Description |
Map.Entry ceilingEntry(K key) | It returns the key-value pair having the least key, greater than or equal to the specified key, or null if there is no such key. |
K ceilingKey(K key) | It returns the least key, greater than the specified key or null if there is no such key. |
void clear() | It removes all the key-value pairs from a map. |
Object clone() | It returns a shallow copy of TreeMap instance. |
Comparator comparator() | It returns the comparator that arranges the key in order, or null if the map uses the natural ordering. |
NavigableSet descendingKeySet() | This method returns a reverse order NavigableSet view of the keys contained in the map. |
NavigableMap descendingMap() | It returns the specified key-value pairs in descending order. |
Map.Entry firstEntry() | It returns the key-value pair having the least key. |
Map.Entry floorEntry(K key) | It returns the greatest key, less than or equal to the specified key, or null if there is no such key. |
void forEach(BiConsumer action) | It performs the mention action for each entry in the map until all entries processed or the action throws an exception. |
SortedMap headMap(K toKey) | It returns the key-value pairs whose keys are strictly less than toKey. |
NavigableMap headMap(K toKey, boolean inclusive) | It returns the key-value pairs whose keys are less than (or equal to if inclusive is true) toKey. |
Map.Entry higherEntry(K key) | It returns the least key strictly greater than the given key, or null if there is no such key. |
K higherKey(K key) | It is used to return true if map contains a mapping for the specified key. |
Set keySet() | It returns the set of keys exist in the map. |
Map.Entry lastEntry() | It returns the key-value pair having the greatest key, or null if there is no such key. |
Map.Entry lowerEntry(K key) | It returns a key and value mapping associated with the greatest key less than the given key or null if there is no such key. |
K lowerKey(K key) | It returns from map the greatest key strictly less than the given key, or null if there is no such key. |
NavigableSet navigableKeySet() | It returns a NavigableSet view of the keys contains in this map. |
Map.Entry pollFirstEntry() | It removes and returns a key-value mapping associated with the least key in this map, or null if the map is empty. |
Map.Entry pollLastEntry() | It removes and returns a key and value mapping associated with the greatest key in this map, or null if the map is empty. |
V put(K key, V value) | It inserts the specified value with respect to key in the map. |
void putAll(Map map) | It is used to copy all the key-value pair from one map to another map. |
V replace(K key, V value) | It replaces the value with respect to key. |
boolean replace(K key, V oldValue, V newValue) | It replaces the old value with the new value with respect to key. |
void replaceAll(BiFunction function) | It replaces each entry’s value with the result of invoking the mentioned function on all entries have been processed or the function throw an exception. |
NavigableMap subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive) | It returns key and value pairs whose keys match with in range fromKey to toKey. |
SortedMap subMap(K fromKey, K toKey) | It returns key and value pairs whose keys range match fromKey, inclusive, to toKey, exclusive. |
SortedMap tailMap(K fromKey) | It returns key and value pairs whose keys are greater than or equal to fromKey. |
NavigableMap tailMap(K fromKey, boolean inclusive) | It returns key and value pairs whose keys are greater than (o equal to, if inclusive is true) fromKey. |
boolean containsKey(Object key) | It returns true if the map contains a mapping with respect to key. |
boolean containsValue(Object value) | It returns true if the map find one or more keys to the specified value. |
K firstKey() | It is used to return the first find lowest key currently in this sorted map. |
V get(Object key) | It is used to return the value to which the map maps the specified key. |
K lastKey() | It is used to return the last highest key currently in the sorted map. |
V remove(Object key) | It removes the key and value pair of the specified key from the map. |
Set entrySet() | It returns a set of the mappings contained in the map. |
int size() | It returns the number of key-value pairs that exists in the hashtable. |
Collection values() | It returns a collection of values contained in the map. |
TreeMap Example : insert and traverse elements
import java.util.Map; import java.util.TreeMap; class TreeMapExample1{ public static void main(String args[]){ TreeMap<Integer,String> map=new TreeMap<Integer,String>(); map.put(20,"Anuj"); map.put(22,"Ravi"); map.put(21,"Virendra"); map.put(23,"Raghav"); for(Map.Entry m:map.entrySet()){ System.out.println(m.getKey()+" "+m.getValue()); } } }
Output :
20 Anuj
21 Virendra
22 Ravi
23 Raghav
TreeMap Example : remove() elements
import java.util.*; public class TreeMapExample2 { public static void main(String args[]) { TreeMap<Integer, String> map = new TreeMap<Integer, String>(); map.put(20, "Anuj"); map.put(22, "Ravi"); map.put(21, "Virendra"); map.put(23, "Raghav"); System.out.println("\nBefore invoking remove() method"); for (Map.Entry m : map.entrySet()) { System.out.println(m.getKey() + " " + m.getValue()); } map.remove(22); System.out.println("\nAfter invoking remove() method"); for (Map.Entry m : map.entrySet()) { System.out.println(m.getKey() + " " + m.getValue()); } } }
Output :
Before invoking remove() method
20 Anuj
21 Virendra
22 Ravi
23 Raghav
After invoking remove() method
20 Anuj
21 Virendra
23 Raghav
Treemap Example : with NavigableMap
import java.util.*; import java.util.NavigableMap; import java.util.TreeMap; class TreeMapExample3 { public static void main(String args[]) { NavigableMap<Integer, String> map = new TreeMap<Integer, String>(); map.put(20, "Anuj"); map.put(22, "Ravi"); map.put(21, "Virendra"); map.put(23, "Raghav"); // Maintains descending order System.out.println("\ndescendingMap: " + map.descendingMap()); // Returns key-value pairs whose keys are less than or equal to the // specified key. System.out.println("\nheadMap: " + map.headMap(22, true)); // Returns key-value pairs whose keys are greater than or equal to the // specified key. System.out.println("\ntailMap: " + map.tailMap(22, true)); // Returns key-value pairs exists in between the specified key. System.out.println("\nsubMap: " + map.subMap(20, false, 22, true)); } }
Output :
descendingMap: {23=Raghav, 22=Ravi, 21=Virendra, 20=Anuj}
headMap: {20=Anuj, 21=Virendra, 22=Ravi}
tailMap: {22=Ravi, 23=Raghav}
subMap: {21=Virendra, 22=Ravi}
TreeMap Example : SortedMap()
import java.util.*; import java.util.SortedMap; import java.util.TreeMap; class TreeMapExample4 { public static void main(String args[]) { SortedMap<Integer, String> map = new TreeMap<Integer, String>(); map.put(20, "Anuj"); map.put(22, "Ravi"); map.put(21, "Virendra"); map.put(23, "Raghav"); // Returns key-value pairs whose keys are less than the specified key. System.out.println("\nheadMap: " + map.headMap(22)); // Returns key-value pairs whose keys are greater than or equal to the // specified key. System.out.println("\ntailMap: " + map.tailMap(22)); // Returns key-value pairs exists in between the specified key. System.out.println("\nsubMap: " + map.subMap(20, 22)); } }
Output :
headMap: {20=Anuj, 21=Virendra}
tailMap: {22=Ravi, 23=Raghav}
subMap: {20=Anuj, 21=Virendra}
TreeMap Example : with objects
import java.util.*; class Magzine{ int id; String name,author,publisher; int quantity; public Magzine(int id, String name, String author, String publisher, int quantity) { this.id = id; this.name = name; this.author = author; this.publisher = publisher; this.quantity = quantity; } } import java.util.Map; import java.util.TreeMap; public class HashtableExampleWithObjects { public static void main(String[] args) { // Creating map of Magzine Map<Integer, Magzine> table = new TreeMap<Integer, Magzine>(); // Creating Magzines Magzine m1 = new Magzine(21, "The Sun", "Sy Sunfranchy", "The Sun Company", 8); Magzine m2 = new Magzine(22, "Glimmer Trains", "Unknown", "Glimmer Train Press", 4); Magzine m3 = new Magzine(23, "Crazy horse", "Brett Lot", "College of Charleston", 6); // Adding magzine to map table.put(1, m1); table.put(2, m2); table.put(3, m3); // Traversing map for (Map.Entry<Integer, Magzine> entry : table.entrySet()) { int key = entry.getKey(); Magzine m = entry.getValue(); System.out.println("\nId: "+key + " Details:"); System.out.println(m.id + " " + m.name + " " + m.author + " " + m.publisher + " " + m.quantity); } } }
Output :
Id: 1 Details:
21 The Sun Sy Sunfranchy The Sun Company 8
Id: 2 Details:
22 Glimmer Trains Unknown Glimmer Train Press 4
Id: 3 Details:
23 Crazy horse Brett Lot College of Charleston 6
You must log in to post a comment.