Java TreeMap Class is Red-Black tree based NavigableMap implementation. TreeMap is sorted according to the natural ordering of its keys, or by a Comparator provided at creation time, depending on which constructor is used.TreeMap Class implemente Map interface and it is similar like hashmap except that it have sorted element.
TreeMap Hierarchy
Java TreeMap Class implements the NavigableMap interface, which in turn extends the SortedMap interface. TreeMap class have below declaration
public class TreeMap<K,V>
extends AbstractMap<K,V>
implements NavigableMap<K,V>, Cloneable, java.io.Serializable{
//more code here
}

TreeMap Features
- Java TreeMap implements the NavigableMap interface and extends AbstractMap class.
- HashMap contains only unique keys like hashmap.
- Java TreeMap not alllowed null key but can have multiple null values.
- The elements in a TreeMap are sorted as per natural ordering, or based on a given Comparator that is supplied at the time of creation of TreeMap
- Java TreeMap is non-synchronize so it is not thread-safe. You must explicitly synchronize concurrent modifications to the TreeMap as
Map s = Collections.synchronizedSet(new TreeMap(…)); - The iterators returned by this class’s iterator method are fail-fast.It means if the set is modified at any time after the iterator is created, in any way except through the iterator’s own remove method, the iterator will throw a ConcurrentModificationException.
Constructors of Java TreeMap class
Java TreeMap Class have these constructors as per below.
- TreeMap() – Constructs a new, empty tree map, using the natural ordering of its keys.
- TreeMap(Comparator<? super K> comparator) – Constructs a new, empty tree map, ordered according to the given comparator.
- TreeMap(Map<? extends K,? extends V> m) – Constructs a new tree map containing the same mappings as the given map, ordered according to the natural ordering of its keys.
- TreeMap(SortedMap<K,? extends V> m) – Constructs a new tree map containing the same mappings and using the same ordering as the specified sorted map.
Creating and add element to TreeMap
Now we will create TreeMap in Java and add element in this using put() method.
import java.util.TreeMap;
public class TreeMapExample {
public static void main(String[] args) {
/*
* Constructs a new, empty tree map,
* using the natural ordering of its keys
*/
TreeMap<String, String> treeMap = new TreeMap<>();
/*
* Associates the specified value with the specified
* key in this map. If the map previously contained
* a mapping for the key, the old value is replaced.
*/
treeMap.put("hcl", "amit");
treeMap.put("tcs","ravi");
treeMap.put("wipro","anmol");
//display element of treemap
System.out.println("TreeMap Element ="+ treeMap);
}
}
Output :
TreeMap Element ={hcl=amit, tcs=ravi, wipro=anmol}
Iterating a TreeMap
We have different ways of iterating over a HashMap as following –
- Iterating the TreeMap using entrySet.
- Iterating the TreeMap using simple for-each loop.
Let’s see these thing by code example
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
public class TreeMapExample {
public static void main(String[] args) {
/*
* Constructs a new, empty tree map,
* using the natural ordering of its keys
*/
TreeMap<String, String> treeMap = new TreeMap<>();
/*
* Associates the specified value with the specified
* key in this map. If the map previously contained
* a mapping for the key, the old value is replaced.
*/
treeMap.put("hcl", "amit");
treeMap.put("tcs","ravi");
treeMap.put("wipro","anmol");
System.out.println("====>> Iterating TreeMap using entrySet ===>>");
Set<Map.Entry<String, String>> employeeEntries = treeMap.entrySet();
Iterator<Map.Entry<String, String>> employeeIterator = employeeEntries.iterator();
while (employeeIterator.hasNext()) {
Map.Entry<String, String> entry = employeeIterator.next();
System.out.println("Key Of map = "+ entry.getKey() + " , value of map = " + entry.getValue() );
}
System.out.println("===>> Iterating TreeMap using entrySet with simple for-each loop ===>>");
for(Map.Entry<String, String> entry: treeMap.entrySet()) {
System.out.println("Key Of map = "+ entry.getKey() + " , value of map = " + entry.getValue() );
}
}
}
Output:
====>> Iterating TreeMap using entrySet ===>>
Key Of map = hcl , value of map = amit
Key Of map = tcs , value of map = ravi
Key Of map = wipro , value of map = anmol
===>> Iterating TreeMap using entrySet with simple for-each loop ===>>
Key Of map = hcl , value of map = amit
Key Of map = tcs , value of map = ravi
Key Of map = wipro , value of map = anmol
TreeMap Methods
- Map.Entry<K,V> ceilingEntry(K key) – Returns a key-value mapping associated with the least key greater than or equal to the given key, or null if there is no such key.
- void clear() -Removes all of the mappings from this map.
- Object clone() – Returns a shallow copy of this TreeMap instance.
- Comparator<? super K> comparator() – Returns the comparator used to order the keys in this map, or null if this map uses the natural ordering of its keys.
- boolean containsKey(Object key) – Returns true if this map contains a mapping for the specified key.
- boolean containsValue(Object value) – Returns true if this map maps one or more keys to the specified value.
- NavigableMap<K,V> descendingMap() – Returns a reverse order view of the mappings contained in this map.
- Set<Map.Entry<K,V>> entrySet() – Returns a Set view of the mappings contained in this map.
- Map.Entry<K,V> firstEntry() – Returns a key-value mapping associated with the least key in this map, or null if the map is empty.
- K firstKey() – Returns the first (lowest) key currently in this map.
- Map.Entry<K,V> floorEntry(K key) – Returns a key-value mapping associated with the greatest key less than or equal to the given key, or null if there is no such key.
- K floorKey(K key) – Returns the greatest key less than or equal to the given key, or null if there is no such key.
- V get(Object key) – Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.
- K higherKey(K key) – Returns the least key strictly greater than the given key, or null if there is no such key.
- Set<K> keySet() – Returns a Set view of the keys contained in this map.
- K lastKey() – Returns the last (highest) key currently in this map.
- Map.Entry<K,V> lowerEntry(K key) – Returns a key-value mapping associated with the greatest key strictly less than the given key, or null if there is no such key.
- Map.Entry<K,V> pollFirstEntry() – Removes and returns a key-value mapping associated with the least key in this map, or null if the map is empty.
- Map.Entry<K,V> pollLastEntry() -Removes and returns a key-value mapping associated with the greatest key in this map, or null if the map is empty.
- V put(K key, V value) – Associates the specified value with the specified key in this map.
- void putAll(Map<? extends K,? extends V> map) – Copies all of the mappings from the specified map to this map.
- V remove(Object key) – Removes the mapping for this key from this TreeMap if present.
- V replace(K key, V value) – Replaces the entry for the specified key only if it is currently mapped to some value.
- boolean replace(K key, V oldValue, V newValue) – Replaces the entry for the specified key only if currently mapped to the specified value.
- void replaceAll(BiFunction<? super K,? super V,? extends V> function) – Replaces each entry’s value with the result of invoking the given function on that entry until all entries have been processed or the function throws an exception.
- int size() – Returns the number of key-value mappings in this map.
Java treemap example
Now we will see more java treemap example step by steps .