Java TreeMap Examples

Java TrreMap Class is Red-Black tree based NavigableMap implementation. TrreMap 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

}
java treemap class hierarchy
                                         java TreeMap class hierarchy

TreeMap Features

  1. Java TreeMap implements the NavigableMap interface and extends AbstractMap class.
  2. HashMap contains only unique keys like hashmap.
  3. Java TreeMap not alllowed null key but can have multiple null values.
  4. 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
  5. 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(…));
  6. 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.
  1. TreeMap() – Constructs a new, empty tree map, using the natural ordering of its keys.
  2. TreeMap(Comparator<? super K> comparator) – Constructs a new, empty tree map, ordered according to the given comparator.
  3. 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.
  4. 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

  1. 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.
  2. void clear() -Removes all of the mappings from this map.
  3. Object clone() – Returns a shallow copy of this TreeMap instance.
  4. 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.
  5. boolean containsKey(Object key) – Returns true if this map contains a mapping for the specified key.
  6. boolean containsValue(Object value) – Returns true if this map maps one or more keys to the specified value.
  7. NavigableMap<K,V> descendingMap() – Returns a reverse order view of the mappings contained in this map.
  8. Set<Map.Entry<K,V>> entrySet() – Returns a Set view of the mappings contained in this map.
  9. 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.
  10. K firstKey() – Returns the first (lowest) key currently in this map.
  11. 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.
  12. K floorKey(K key) – Returns the greatest key less than or equal to the given key, or null if there is no such key.
  13. 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.
  14. K higherKey(K key) – Returns the least key strictly greater than the given key, or null if there is no such key.
  15. Set<K> keySet() – Returns a Set view of the keys contained in this map.
  16. K lastKey() – Returns the last (highest) key currently in this map.
  17. 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.
  18. 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.
  19. 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.
  20. V put(K key, V value) – Associates the specified value with the specified key in this map.
  21. void putAll(Map<? extends K,? extends V> map) – Copies all of the mappings from the specified map to this map.
  22. V remove(Object key) – Removes the mapping for this key from this TreeMap if present.
  23. V replace(K key, V value) – Replaces the entry for the specified key only if it is currently mapped to some value.
  24. boolean replace(K key, V oldValue, V newValue) – Replaces the entry for the specified key only if currently mapped to the specified value.
  25. 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.
  26. int size() – Returns the number of key-value mappings in this map.

TreeMap Other Tutorials

Leave a Reply

Your email address will not be published. Required fields are marked *

64 − 63 =