Java

Java – TreeMap With Example

TreeMap is an implementation of NavigableMap based on Red-Black trees. It is arranged in the order that its keys naturally appear.
Similar to the HashMap class, the TreeMap class implements the Map interface. The primary distinction between both is that TreeMap is sorted in the ascending order of its keys, while HashMap is an unordered collection. TreeMap is an unsynchronized collection class, hence unless explicitly synchronized, it cannot be used for thread-safe operations.

TreeMap Example

In this example, we store the key and value mappings in the TreeMap and get the data from the TreeMap to obtain a sorted key-value mapping.

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

public class Details {

   public static void main(String args[]) {

      /* This is how to declare TreeMap */
      TreeMap<Integer, String> tmap = 
             new TreeMap<Integer, String>();

      /*Adding elements to TreeMap*/
      tmap.put(1, "Data1");
      tmap.put(23, "Data2");
      tmap.put(70, "Data3");
      tmap.put(4, "Data4");
      tmap.put(2, "Data5");

      /* Display content using Iterator*/
      Set set = tmap.entrySet();
      Iterator iterator = set.iterator();
      while(iterator.hasNext()) {
         Map.Entry mentry = (Map.Entry)iterator.next();
         System.out.print("key is: "+ mentry.getKey() + " & Value is: ");
         System.out.println(mentry.getValue());
      }

   }
}

Output:

key is: 1 & Value is: Data1
key is: 2 & Value is: Data5
key is: 4 & Value is: Data4
key is: 23 & Value is: Data2
key is: 70 & Value is: Data3

As you can see, the data was input in a random order, but when the TreeMap’s content was presented, the results were sorted in ascending order of keys.

Related Articles

Leave a Reply

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

Back to top button