Java TreeMap : Collection Class



Java TreeMap : Collection Class

  1. TreeMap class implements the Map interface by using a tree
  2. TreeMap provides an efficient means of storing key/value pairs in sorted order
  3. TreeMap allows faster retrieval of elements.
  4. Tree map elements will be sorted in ascending key order.

Lets create an TreeMap using following line of code -

Example #1 : Create TreeMap

package com.c4learn.collection;
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) {
    TreeMap<Integer, String> tMap = new 
                        TreeMap<Integer, String>();
    tMap.put(101, "Aman");
    tMap.put(108, "Arun");
    tMap.put(102, "Akash");
    tMap.put(190, "Aniket");
    tMap.put(182, "Anil");
    Set set = tMap.entrySet();
    Iterator itr = set.iterator();
    while (itr.hasNext()) {
      Map.Entry m = (Map.Entry) itr.next();
      System.out.println(m.getKey() + " " + m.getValue());
    }
  }
}

Output :

101 Aman
102 Akash
108 Arun
182 Anil
190 Aniket