TreeMap add Sort Compare Java

Two programs are given on TreeMap with the following operations.

  1. TreeMap General: The general operations like object creation, addition and deletion of key/value pairs, knowing the existence of a key or value or elements and size etc. are performed.
  2. TreeMap Special: The special operations like sorting the elements on key basis and value basis, adding elements (key/value pairs) of one tree map to another at object creation and later, extracting a part of a tree map into another etc. are shown.

This is the second program of the above two where special and rare operations (like TreeMap add Sort Compare) are performed. Before going into this program, it is advised to go through TreeMap Tutorial and also to know first about the Map, SortedMap interfaces and Map methods as TreeMap is derived from them and uses as it is all the methods of Map interface.

Example on TreeMap add Sort Compare Java
import java.util.*;
public class TreeMapSpecial
{
  public static void main(String args[])
  {
    TreeMap tm1 = new TreeMap();  
    tm1.put("banana", 20);
    tm1.put("apple", 50);
    tm1.put("melon", 40);
    tm1.put("guava", 20);
    tm1.put("cherry", 30);

    System.out.println("\nElements of tm1: " + tm1);
    Set mySet = tm1.keySet();
    System.out.println("Keys of tm1: " + mySet);

    Collection myCol = tm1.values();
    System.out.println("Values of tm1: " + myCol);

			                               // USING ITERATOR
    System.out.print("\nPrinting keys with Iterator: ");
    Iterator it1 = mySet.iterator();
    while(it1.hasNext())
    {
      System.out.print(it1.next() + ", ");
    } 
			                               // TREEMAP SORT BY VALUE
    TreeSet yourSet = new TreeSet();
    yourSet.addAll(myCol);
    System.out.println("\nTreeMap sort by value: " + yourSet);

			                               // COMPARING TWO TREE MAPS
    TreeMap tm2 = new TreeMap();  
    tm2.putAll(tm1);
    System.out.println("\nElements of tm2: " + tm2);
    if(tm1.equals(tm2))
    {
     System.out.println("tm1 and tm2 contain same elements\n");
    } 

    System.out.println("\t\tEXTRACTING TREEMAP ELEMENTS\n");

    SortedMap m1 = tm1.subMap("banana", "guava");
    System.out.println("subMap(\"banana\", \"guava\"): " + m1);

    SortedMap m2 = tm1.headMap("guava");
    System.out.println("headMap(\"guava\"): " + m2);

    SortedMap m3 = tm1.tailMap("guava");
    System.out.println("tailMap(\"guava\"): " + m3);
   }
}


TreeMap add Sort Compare Java
Output screen on TreeMap add Sort Compare Java

     TreeMap tm1 = new TreeMap();  
     tm1.put("banana", 20);

After knowing the simple operations, let us go for special operations. For this, A generic TreeMap object tm1 is created that stores keys as strings and values as integers.

     Set mySet = tm1.keySet();
     System.out.println("Keys of tm1: " + mySet);

The keySet() method, inherited from Map interface, returns all the keys as Set object, mySet. As TreeMap is derived from SortedMap, the keys are printed in ascending order by default. What is the designing principle of returning a Set object by keySet() method is discussed in "interface Map Methods".

     Collection myCol = tm1.values();

Like keySet() returns all the keys, the values() method returns a Collection object, myCol. Now myCol prints all the values. Observe, the values are printed as per the sorted key order (not addition order).

     System.out.print("\nPrinting keys with Iterator: ");
     Iterator it1 = mySet.iterator();
     while(it1.hasNext())
     {
       System.out.print(it1.next() + ", ");
     } 

Using iterator() method of Set interface, all the elements of mySet are iterated and printed. The iterator() method returns an object of Iterator interface, The internal working principle of hasNext() and next() methods is clearly discussed in Iterator Intrerface.

     TreeSet yourSet = new TreeSet();
     yourSet.addAll(myCol);

The keys returned by keySet() method are sorted automatically (as TreeMap sorts by keys implicitly) but the values returned by values() methods are not. It requires extra code. Here, a simple technique is followed. The elements of myCol object, returned by values() method, are added to TreeSet with addAll() method, inherited from Collection interface. The TreeSet sorts automatically.

     TreeMap tm2 = new TreeMap();  
     tm2.putAll(tm1);

Another TreeMap object tm2 is created and added with all the elements of tm1 with putAll() method, inherited from Map interface. It is required to the programmer to know which method is coming from where and if possible how the method works internally.

     if(tm1.equals(tm2))
     {
       System.out.println("tm1 and tm2 contain same elements\n");
     } 

The equals() inherited from Map compares two Map objects and if the elements (here, key/value pairs) are same, the method returns true. The order of elements is not of importance.

     SortedMap m1 = tm1.subMap("banana", "guava");
     SortedMap m2 = tm1.headMap("guava");
     SortedMap m3 = tm1.tailMap("guava");

There are three methods to extract the elements of a TreeMap, subMap(), headMap() and tailMap() and are clearly discussed in SortedMap interface (with extra precautions to be taken for subMap()) as these methods are defined in SortedMap and inherited by TreeMap.

Leave a Comment

Your email address will not be published.