Java treemap

Hey guys!! Welcome to flower brackets blog. Today we are going to learn java treemap.

Treemap class is part of java collection framework. It’s always sorted based on key. Treemap is red black tree based implementation of map interface.

Tree map can’t contain duplicate key and null key. It can have more than one “null” values. Treemap is sorted according to the natural ordering of its keys.

If you want to sort using different order then you need to provide your own custom Comparator to treemap which depends on constructor used.

Treemap is not thread safe. It should be synchronized externally using Collections.synchronizedSortedMap(map) method. Hence affecting performance.

Treemap method while getting key and values return iterator method which are fail-fast and if the map is structurally modified will throw a ConcurrentModificationException.

Hierarchy of Treemap Class

java treemap

Treemap class implements navigablemap interface. Navigablemap interface extends sortedmap interface. Sortedmap interface extends map interface.

SortedMap and NavigableMap function is to maintain order of keys and navigate through map. Here TreeMap implements both SortedMap and NavigableMap.

Treemap class belongs to java.util package.

Class TreeMap< K,V >

Here you can see K comma V. K is type of keys to maintain the treemap. V is a type of values maintain the treemap.

java.lang.Object
     java.util.AbstractMap<K,V>
          java.util.TreeMap<K,V>

Treemap class extends abstractmap class, abstractmap class extends object class.

Serializable, Cloneable, Map<K,V>, NavigableMap<K,V>, SortedMap<K,V>


Let’s see how to create simple treemap,

import java.util.Comparator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

public class TreemapExample 
{
   static class SubjectCompare implements Comparator<String>
   {
      // here we are comparing keys based on the last word's natural ordering
      public int compare(String x, String y) 
      { 
         int a, b, c;
         a = x.lastIndexOf(' '); 
         b = y.lastIndexOf(' '); 
         c = x.substring(a).compareToIgnoreCase(y.substring(b)); 
         if(c == 0)
         {
            return x.compareToIgnoreCase(y);
         }
         else
         {
            return c;
         }
      } 
   }

   public static void main(String[] args) 
   {
      TreeMap<String, Integer> tree = new TreeMap<>(new SubjectCompare()); 

      tree.put("Optimization Techniques", 010);
      tree.put("Data Structures", 102); 
      tree.put("Fundamental of Electronics", 106); 
      tree.put("Electrodynamics and Optics", 005); 
      tree.put("Ethics and Self Awareness", 002); 

      // here values can be null 
      tree.put("HSS Elective Course", null); 

      // last entry with the same key 
      // reflected in output 
      tree.put("HSS Elective Course", 006); 

      Set<Map.Entry<String, Integer>> set = tree.entrySet(); 
         for(Map.Entry<String,Integer> me : set) 
            System.out.println(me.getKey() + " : " + me.getValue());

         System.out.println("--------------------------------");

         tree.remove("Data Structures"); 
         System.out.println("After removal of subject : Data Structures - "); 
         for(Map.Entry<String,Integer> me : set) 
            System.out.println(me.getKey() + " : " + me.getValue());
   }
}

Output :

Ethics and Self Awareness : 2
HSS Elective Course : 6
Fundamental of Electronics : 106
Electrodynamics and Optics : 5
Data Structures : 102
Optimization Techniques : 8
——————————–
After removal of subject : Data Structures –
Ethics and Self Awareness : 2
HSS Elective Course : 6
Fundamental of Electronics : 106
Electrodynamics and Optics : 5
Optimization Techniques : 8


Methods of treemap

Methods - modifierDescription
Object firstKey()returns the first (lowest) key currently in this sorted map
Object get(Object key)returns the value to which this map maps the specified key
Object clone()This method returns a shallow copy of this TreeMap instance
void clear()This method removes all mappings from this TreeMap and clears the map.
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 contains a mapping for the specified value.
NavigableSet descendingKeySet()Returns a reverse order NavigableSet view of the keys contained in this map.
NavigableMap descendingMap()Returns a reverse order view of the mappings contained in this map.
Set entrySet()returns a Set() view of the mappings contained in this map.
Map.Entry firstEntry()Returns a key value mapping associated with the least key in this map or null if the map is empty.
Map.Entry floorEntry(K key)Returns a key value mapping associated with the greatest key <= the given key or null if there is no such key.
K floorKey(K key)Returns the greatest key <= 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.
SortedMap headMap(K toKey)Returns a view of the portion of this map whose keys are strictly less than toKey.
NavigableMap headMap(K toKey, boolean inclusive)Returns a view of the portion of this map whose keys are less than ( or equal to, if inclusive is true ) toKey.
Map.Entry higherKey(K key)Returns a key-value mapping associated with the least key strictly greater than the given key or null if there is no such key.
K higherKey(K key)Returns the least key strictly greater than the given key or null if there is no such key.
Set keySet()Returns a Set view of the keys contained in this map.
Map.Entry lastEntry()Returns a key-value mapping associated with the greatest key in this map or null if the map is empty.
Object lastKey()Returns the last(highest) key currently in this map.
Map.Entry 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.
K lowerKey(K key)Returns the greatest key strictly less than the given key or null if there is no such key.
NavigableSet navigableKeySet()Returns a NavigableSet view of the keys contained in this map.
Map.Entry 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 pollLastEntry()Removes and returns a key value mapping associated with the greatest key in this map or null if the map is empty.
Object put(Object key, Object value)This method is used to insert a mapping into a map.
void putAll(Map map)Copies all of the mappings from the specified map to this map.
Object remove(Object key)removes the mapping for this key from this TreeMap if present.
int size()returns the number of key value mappings in this map.
NavigableMap subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive)Returns a view of the portion of this map whose keys range fromKey to toKey.
SortedMap subMap(K fromKey, K toKey)Returns a view of the portion of this map whose keys range from fromKey, inclusive to toKey, exclusive.
SortedMap tailMap(K fromKey)Returns a view of the portion of this map whose keys are greater than or equal to fromKey.
NavigableMap tailMap(K fromKey, boolean inclusive)Returns a view of the portion of this map whose keys are greater than ( or equal to, if inclusive is true ) fromKey.
Collection values()Returns a Collection view of the values contained in this map.

Methods inherited from class java.util.AbstractMap
equals, hashCode, isEmpty, toString

Methods inherited from class java.lang.Object
finalize, getClass, notify, notifyAll, wait, wait, wait

Methods inherited from interface java.util.Map
equals, hashCode, isEmpty


Java treemap constructors

Here we will discuss treemap constructors.

public TreeMap()

This is the default one. Using this constructor we can create empty treemap and once you create empty treemap it will be sorted using natural order of its keys.


public TreeMap(Map<? extends K, ? extends V> m)

which accepts map and sorted using natural order of keys.


public TreeMap(SortedMap<K, ? extends V> m)

which accepts sortedmap and initializes treemap with entries from sortedmap.


public TreeMap(Comparator<? super K> comparator)

which accepts Comparator object and constructs an empty treemap and after that sorts using Comparator.


Reference – Oracle Docs

Related Posts