TreeMap in java with example


We will cover following points of TreeMap in Java:

    1. Basic Points about TreeMap.
    2. Different ways to iterate TreeMap in Java.
    3. Constructors and methods of TreeMap in Java.

Basics of TreeMap in Java

  1. TreeMap is a class which extends AbstractMap and implements NavigableMap, Cloneable, Serializable.
  2. TreeMap also used to store the element in the form of key and value pair.
  3. In the TreeMap key must be the same type where value can be the different type.
  4. Key cannot be duplicated where value can be duplicated.
  5. Treemap store the element in sorted order on the basis of the key.
  6. TreeMap uses index representation to store the elements.
  7. In TreeMap value can be null but the key cannot be null. If we try to insert null as a key, the code will compile successfully but at runtime, it will throw NullPointerException.
  8. In Treemap none of the methods are synchronized so it doesn’t affect the concurrency and cloning.

Different ways to iterate TreeMap in Java

Using Iterator – Iterating TreeMap using an iterator.

We will use TreeMap’s entrySet() method which returns a Set type of Map.Entry, something like (Set<Map.Entry<K,V>>).

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

class TreeMapExample {
      public static void main(String[] arg) {
              Map<Integer, String> treemapObject = new TreeMap<>();

                          treemapObject.put(2, "Nadeem");
                          treemapObject.put(3, "Puneet");
                          treemapObject.put(4, "Shyam");
                          treemapObject.put(5, "Sagar");

                                    // we will iterate using Iterator
                        Iterator<Map.Entry<Integer, String>> iterator = treemapObject
                         .entrySet().iterator();

                         while (iterator.hasNext()) {
                           Map.Entry<Integer, String> entry = iterator.next();
                             System.out.println("Key is = " + entry.getKey() + ", Value is = "
                           + entry.getValue());
                          }
             }
}
Using for each loop -Iterating TreeMap using for each loop.

First use entrySet() method then for each loop.

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

public class TreeMapExample1 {
             public static void main(String[] args) {
                    Map<Integer, String> hashMapObj = new TreeMap<>();

                           hashMapObj.put(2, "nadeem");
                           hashMapObj.put(5, "puneet");
                           hashMapObj.put(3, "shyam");

                           Set<Map.Entry<Integer, String>> entrySet = hashMapObj.entrySet();
 
                             for (Map.Entry<Integer, String> entry : entrySet) {
                                  System.out.println("Key is : " + entry.getKey() + " Value is : "
                                   + entry.getValue());
                                   }
          }
}

Using Lambda expression – Iterating TreeMap using lambda expression.

We can also iterate TreeMap using lambda expression as below.

import java.util.TreeMap;
import java.util.Map;

public class TreeMapExample1 {
      public static void main(String[] args) {
         Map<Integer, String> hashMapObj = new TreeMap<>();

           hashMapObj.put(2, "Shyam");
           hashMapObj.put(5, "Puneet");
           hashMapObj.put(3, "Surya");
           hashMapObj.put(9, "Sagar");

           hashMapObj.forEach((k, v) -> {
           System.out.println("Key is : " + k + " Value is : " + v);
           });

      }
}

Using java 8 stream() method –

import java.util.Map;
import java.util.Set;

public class TreeMapExample1 {
        public static void main(String[] args) {
           Map<Integer, String> hashMapObj = new TreeMap<>();

               hashMapObj.put(2, "Puneet");
               hashMapObj.put(5, "Shyam");
               hashMapObj.put(3, "Surya");
               hashMapObj.put(9, "Sagar");

          Set<Map.Entry<Integer, String>> setReference= hashMapObj.entrySet();

             setReference.stream().forEach
             (mapEntry-> System.out.println("Key is : "+mapEntry.getKey()+" Value is :                                                                                       "+mapEntry.getValue()));
        }
}

Constructors and Methods of TreeMap in Java

  • TreeMap()
  • TreeMap(int initialCapacity)
  • TreeMap(int initialCapacity, float loadFactor)
  • TreeMap(Map map)

 


%d bloggers like this: