This Java TreeMap Tutorial Discusses TreeMap Class, Iteration, TreeMap Examples, Implementation, Java Hashmap vs Treemap, TreeMap API Methods etc.:
A TreeMap data structure is a collection that stores key-value pairs in a naturally sorted order. A TreeMap is a part of the Java Collections Framework and is a map implementation.
=> Check ALL Java Tutorials Here.
Table of Contents:
Java TreeMap
Some of the major characteristics of TreeMap in Java are as follows:
- The TreeMap class that implements treemap in Java is a part of java.util package. It implements the Map interface.
- The TreeMap class extends AbstractMap class and also implements the NavigableMap and SortedMap (indirectly) interface.
- TreeMap is not synchronized.
- By default, TreeMap elements are in ascending order by default.
- TreeMap does not allow duplicate elements.
- TreeMap allows null values but not null keys.
The below diagram shows the class hierarchy for the TreeMap class.
As already mentioned, TreeMap class implements a NavigableMap interface that in turn extends the SortedMap class. SortedMap further inherits the map interface.
Declaration Of TreeMap Class
The general declaration of the TreeMap class is given below:
public class TreeMap<K, V> extends AbstractMap<K,V> implements NavigableMap<K, V>, Cloneable, Serializable
where K=> type of keys maintained by TreeMap
V=> type of the mapped values
TreeMap Example
The below program shows a simple example of a TreeMap data structure.
import java.util.*; class Main{ public static void main(String args[]){ //declare a TreeMap and initialize it TreeMap<Integer,String> cities_map=new TreeMap<Integer,String>(); cities_map.put(100,"Pune"); cities_map.put(102,"Jaipur"); cities_map.put(101,"Hyderabad"); cities_map.put(103,"Bangaluru"); //print the TreeMap contents using forEach System.out.println("Contents of TreeMap:"); System.out.print("{"); for(Map.Entry entries:cities_map.entrySet()){ System.out.print(entries.getKey()+" = "+entries.getValue() + " "); } System.out.println("}"); } }
Output:
Contents of TreeMap:
{100 = Pune 101 = Hyderabad 102 = Jaipur 103 = Bangaluru }
In this program, we have defined a simple TreeMap object named, cities_map, and then using the put method, we have initialized it to key-value pairs.
Then we use the entrySet () method of TreeMap class and iterate over this set using a forEach loop to print the key-value pairs. For printing key-value pairs, we use getKey () and getValue () methods respectively.
TreeMap API Methods & Constructors
In this section, we will discuss the various constructors and methods provided by the TreeMap class.
Constructors
Constructor Prototype | Description |
---|---|
TreeMap() | Default constructor to create an empty TreeMap with natural ordering. |
TreeMap ( Comparator < ? super K > comparator ) | Constructs an empty TreeMap which is sorted based on the specified comparator. |
TreeMap ( Map < ? extends K,? extends V > m ) | Constructs a TreeMap and initialized it with the elements of the specified map, m. Ordering is natural. |
TreeMap (SortedMap | Constructs a TreeMap and initialized it with SortedMap entries. Ordering is the same as sortedMap. |
Methods
Method | Method Prototype | Description |
---|---|---|
ceilingEntry | Map.Entry < K,V > ceilingEntry ( K key ) | Returns the least key-value pair such that key is greater than or equal to specified key; null if there is no key |
ceilingKey | K ceilingKey ( K key ) | Returns the key that is least and greater than the given key; returns null if no key. |
clear | void clear () | Deletes all the key-value pairs from the Treemap. |
clone | Object clone () | Makes a shallow copy of TreeMap instance. |
comparator | Comparator < ? super K > comparator () | Returns a comparator used to arrange the keys. null if ordering is natural |
descendingKeySet | NavigableSet < K > descendingKeySet () | Returns NavigableSet view of the TreeMap keys in reverse order. |
descendingMap | NavigableMap < K,V > descendingMap () | Returns given key-value pairs in reverse order. |
firstEntry | Map.Entry firstEntry () | Returns the least key-value pair. |
floorEntry | Map.Entry < K,V > floorEntry (K key) | Returns greatest key which is less than or equal to a given key; null if no such key |
forEach | void forEach (BiConsumer < ? super K,? super V > action ) | The given action is performed for each entry in the TreeMap. |
headMap | SortedMap < K,V > headMap (K toKey) | Used to return a key-value pair such that the returned key is strictly less than toKey |
headMap | NavigableMap < K,V > headMap (K toKey, boolean inclusive ) | Returns key-value pairs of those keys that are less than the toKey or equal to if inclusive. |
higherEntry | Map.Entry < K,V > higherEntry (K key) | Returns the least key or null. The returned key is strictly greater than the given key. |
higherKey | K higherKey (K key) | Returns the key if the mapping is present for the given key in the Treemap. |
keySet | Set keySet () | Returns the set collection of the keys in the TreeMap. |
lastEntry | Map.Entry < K,V > lastEntry () | Returns the key-value pair such that the key is the greatest key. Returns null if the key does not exist. |
lowerEntry | Map.Entry< K,V > lowerEntry (K key) | Returns the key-value pair such that the key is greatest and strictly less than the given key. Returns null if the key does not exist. |
lowerKey | K lowerKey (K key) | Returns the greatest key or null. The returned key is strictly less than the given key. |
navigableKeySet | NavigableSet < K > navigableKeySet () | Returns the ‘NavigableSet’ of keys in the TreeMap. |
pollFirstEntry | Map.Entry < K,V > pollFirstEntry () | Removes and then returns the least key’s key-value pair. |
pollLastEntry | Map.Entry < K,V > pollLastEntry() | Removes and returns the greatest key’s key-value pair. |
put | V put (K key, V value) | Adds given key and value to the TreeMap. |
putAll | void putAll (Map < ? extends K,? extends V > map ) | All the key-value pairs from the given map are copied to the TreeMap. |
replace | V replace ( K key, V value ) | Replaces or changes the value of the given key with the given value. |
replace | boolean replace ( K key, V oldValue, V newValue ) | Replaces oldValue of the given key with newValue. |
replaceAll | void replaceAll ( BiFunction < ? super K, ? super V, ? extends V > function ) | Invokes the given function and replaces all the entries with the result of the function. |
subMap | NavigableMap < K,V > subMap (K fromKey, boolean fromInclusive, K toKey, boolean toInclusive) | Returns the key-value pairs of keys from ‘fromKey’ to ‘toKey’. |
SortedMap | SortedMap < K,V > subMap (K fromKey, K toKey) | Returns key-value pairs for the range fromKey (inclusive) to toKey (exclusive). |
tailMap | SortedMap < K,V > tailMap (K fromKey) | Returns key-value pairs such that the keys are greater than or equal to fromKey. |
tailMap | NavigableMap < K,V > tailMap (K fromKey, boolean inclusive) | Returns key-value pairs for the keys equal to fromKey (inclusive = true) or greater than fromKey. |
containsKey | boolean containsKey (Object key) | Checks if there is a mapping for the given key in the Treemap. Returns true if yes. |
containsValue | boolean containsValue (Object value) | Checks if there is a key mapped with the given value. Returns yes if true. |
firstKey | K firstKey () | Returns the lowest key or the first key in the Sorted Map |
get | V get (Object key) | Retrieves the value mapped to the given key |
lastKey | K lastKey () | Returns last key or highest key in the sorted map. |
remove | V remove (Object key) | Deletes the key-value pair for the given key in the TreeMap |
entrySet | Set < Map.Entry < K,V > > entrySet () | Returns the set for the given TreeMap. |
size | int size () | Returns size or the total number of key-value pairs in the TreeMap. |
values | Collection values () | Returns collection of the values for the TreeMap. |
Iterating Through TreeMap
TreeMap consists of Key-value pairs. TreeMap class provides a method ‘entrySet’ that returns key-value pairs in the map. We can iterate through these entries using the forEach loop and display keys and values using getKey () and getValue () methods respectively.
This is shown in the below Java program:
import java.util.Map; import java.util.TreeMap; class Main { public static void main(String[] arg){ //declare and initialize TreeMap Map<String, String> colorsTree = new TreeMap<String, String>(); colorsTree.put("R", "Red"); colorsTree.put("G", "Green"); colorsTree.put("B", "Blue"); colorsTree.put("M", "Magenta"); System.out.println("The contents of TreeMap:"); // retrieve set of map entries using entrySet method for (Map.Entry<String, String> Map_entry : colorsTree.entrySet()) //print key-value pairs using getKey() and getValue() System.out.println( "[" + Map_entry.getKey() + "=>" + Map_entry.getValue() + "]"); } }
Output:
The contents of TreeMap:
[B=>Blue]
[G=>Green]
[M=>Magenta]
[R=>Red]
TreeMap Implementation In Java
The following Java program demonstrates the main method of the TreeMap class discussed above.
import java.util.Map; import java.util.Map.Entry; import java.util.TreeMap; public class Main { public static void main(String[] args) { //declare a TreeMap Object and initialize it with values TreeMap<Integer,String> map = new TreeMap<>(); for(int i=1;i<=10;i++) { map.put(i, (i*i)+""); } System.out.println("Original Map:" + map); //lowerEntry, higherEntry Entry<Integer,String> entry = map.lowerEntry(4); System.out.println("Closest Lower Entry than 4:"+entry); entry = map.higherEntry(4); System.out.println("Closest Higher Entry than 4:"+entry); System.out.println("Closest Lower key than 4 :"+map.lowerKey(4)); entry = map.floorEntry(6); System.out.println("Closest floor entry than 6: "+entry); entry = map.ceilingEntry(6); System.out.println("Closest ceiling Entry than 6 :"+entry); entry = map.firstEntry(); System.out.println("TreeMap First Entry:"+entry); entry = map.lastEntry(); System.out.println("TreeMap Last Entry:"+entry); Map<Integer, String> reversedMap = map.descendingMap(); System.out.println("Reversed TreeMap: "+reversedMap); //pollFirstEntry, pollLastEntry entry = map.pollFirstEntry(); System.out.println("TreeMap First Entry:"+entry); entry = map.pollLastEntry(); System.out.println("TreeMap Last Entry:"+entry); //subMap Map<Integer, String> subMap = map.subMap(2, true, 6, true); System.out.println("Submap from 2 to 6: "+subMap); //headMap subMap = map.headMap(5, true); System.out.println("HeadMap: "+subMap); //tailMap subMap = map.tailMap(5, true); System.out.println("TailMap: "+subMap); } }
Output:
Original Map:{1=1, 2=4, 3=9, 4=16, 5=25, 6=36, 7=49, 8=64, 9=81, 10=100}
Closest Lower Entry than 4:3=9
Closest Higher Entry than 4:5=25
Closest Lower key than 4 :3
Closest floor entry than 6: 6=36
Closest ceiling Entry than 6 :6=36
TreeMap First Entry:1=1
TreeMap Last Entry:10=100
Reversed TreeMap: {10=100, 9=81, 8=64, 7=49, 6=36, 5=25, 4=16, 3=9, 2=4, 1=1}
TreeMap First Entry:1=1
TreeMap Last Entry:10=100
Submap from 2 to 6: {2=4, 3=9, 4=16, 5=25, 6=36}
HeadMap: {2=4, 3=9, 4=16, 5=25}
TailMap: {5=25, 6=36, 7=49, 8=64, 9=81}
Sort TreeMap By Value
By Default, TreeMap is sorted based on the keys according to natural ordering. But if we want to sort the TreeMap according to the values, then we have to make use of the comparator to define the sorting.
The below Java program sorts the TreeMap by value.
import java.util.*; class Main { //Method for sorting the TreeMap based on values public static <K, V extends Comparable<V>> Map<K, V> sortTreeMap(final Map<K, V> map) { //define a comaprator to sort TreeMap on values Comparator<K> valueComparator = new Comparator<K>() { public int compare(K k1, K k2) { int compare = map.get(k1).compareTo(map.get(k2)); if (compare == 0) return 1; else return compare; } }; //use the comparator to sort the TreeMap and return sortedTreeMap Map<K, V> sortedTreeMap = new TreeMap<K, V>(valueComparator); sortedTreeMap.putAll(map); return sortedTreeMap; } public static void main(String args[]) { //define and initialize the TreeMap TreeMap<String, String> treemap = new TreeMap<String, String>(); treemap.put("R", "Red"); treemap.put("G", "Green"); treemap.put("B", "Blue"); treemap.put("C", "Cyan"); treemap.put("M", "Magenta"); // call method sortTreeMap to sort the TreeMap Map sortedTreeMap = sortTreeMap(treemap); // Retrieve set of the entries on the sorted map Set set = sortedTreeMap.entrySet(); System.out.println("The sorted TreeMap based on Values:"); // Now define iterator on this set Iterator i = set.iterator(); // Print TreeMap elements while(i.hasNext()) { Map.Entry me = (Map.Entry)i.next(); System.out.print(me.getKey() + ": "); System.out.println(me.getValue()); } } }
Output:
The sorted TreeMap is based on Values:
B: Blue
C: Cyan
G: Green
M: Magenta
R: Red
Java Hashmap vs Treemap
Let’s see some of the major differences between a HashMap and TreeMap.
The below table shows these differences.
HashMap | TreeMap |
---|---|
Implements the Map interface. | Implements NavigableMap interface. |
Uses hashing implementation technique | Use a red-black tree for implementation |
Does not maintain any order of containing elements | The Keys in the treemap are already ordered as per natural ordering |
Allows one null key and many null values | Allows only null values but keys cannot be null |
Performs basic operations, put and get in constant time. | Take log (n) time to perform put and get operations |
HashMap has limited functionality. | TreeMap class provides lots of additional functionality that help us manipulate the data structure. |
HashMap is much faster than TreeMap. | TreeMap is slower |
Uses equals () method for comparing. | Uses compareTo () method for comparing. |
Frequently Asked Questions
Q #1) What is TreeMap in Java?
Answer: TreeMap in Java is a collection of key-value pairs that are already sorted. It uses a red-black tree for implementation purposes. Java TreeMap implements the NavigableMap interface apart from the Map interface and also extends AbstractMap class.
Q #2) Why do we use TreeMap in Java?
Answer: The TreeMap is used in Java for implementing Map and NavigableMap interfaces and AbstractMap class. As the TreeMap keys are sorted as per the natural ordering, we can use this data structure for storing directory structure, tree hierarchies, etc.
Q #3) Which is better – HashMap or TreeMap?
Answer: HashMap is better than TreeMap. HashMap always takes constant time to perform basic operations while TreeMap takes log (n) time to perform these operations. When larger data objects are involved, HashMap performs faster when compared to TreeMap.
Q #4) Is TreeMap sorted?
Answer: Yes, the key entries in TreeMap are sorted according to natural ordering. TreeMap class also allows us to use a custom comparator to sort the TreeMap based on values.
Q #5) Is TreeMap thread-safe?
Answer: No, TreeMap is not a thread-safe collection.
Conclusion
In this tutorial, we discussed TreeMap in Java in detail. TreeMap is a collection of key-value pairs that implements a map interface. It also implements a NavigableMap interface. The elements of the TreeMap are unique and no duplicates are allowed.
We saw the constructors and methods of TreeMap. We also implemented the TreeMap program and demonstrated the major methods of the TreeMap class. Then we discussed the differences between HashMap and TreeMap.
=> Visit Here To See The Java Training Series For All.