TreeMap in java with examples

TreeMap class implements Map similar to HashMap.

Some important points about TreeMap:
  1. TreeMap implements Map interface and extends HashMap class.
  2. TreeMap is implemented using Red black tree based NavigableMap.
  3. TreeMap is ordered collection and store its elements in natural ordering of keys.
  4. Key which you would like to put in TreeMap must implement Comaparable interface or you can use Comparator for custom sorting
Example:
package org.arpit.java2blog;

import java.util.TreeMap;

public class TreeMapMain {

 public static void main(String args[])
 {
 // TreeMap with Country as key and capital as value
 // TreeMap stores elements in natural ordering of keys. 
  TreeMap<String,String> countryCapitalMap=new TreeMap<String,String>();
  countryCapitalMap.put("India","Delhi");
  countryCapitalMap.put("Japan","Tokyo");
  countryCapitalMap.put("France","Paris");
  countryCapitalMap.put("Russia","Moscow");

  System.out.println("-----------------------------");
  // Iterating TreeMap Using keySet() and for each loop
  System.out.println("Iterating TreeMap Using keySet() and for each loop");
  for (String countryKey:countryCapitalMap.keySet()) {
   System.out.println("Country:"+ countryKey +" and  Capital:"+countryCapitalMap.get(countryKey));

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

}

When you run above program, you will get following output:
-----------------------------
Iterating TreeMap Using keySet() and for each loop
Country:France and  Capital:Paris
Country:India and  Capital:Delhi
Country:Japan and  Capital:Tokyo
Country:Russia and  Capital:Moscow
-----------------------------

As you can see, it is sorted in ascending order of Key(Country)

What if you want custom sorting rather than natural ordering:

If you want custom sorting , then you can using below TreeMap constructor. You can define your own comparator.
 TreeMap countryCapitalMap=new TreeMap(Comparator comp);
Example: Create Country.java as below
package org.arpit.java2blog;  
public class Country {  
  
 String name;  
 long population;  
   
 public Country(String name, long population) {  
  super();  
  this.name = name;  
  this.population = population;  
 }  
 public String getName() {  
  return name;  
 }  
 public void setName(String name) {  
  this.name = name;  
 }  
 public long getPopulation() {  
  return population;  
 }  
 public void setPopulation(long population) {  
  this.population = population;  
 }  
       
}  
Create TreeMapCompMain as below:
package org.arpit.java2blog;

import java.util.Comparator;
import java.util.Iterator;
import java.util.TreeMap;

public class TreeMapCompMain {

 public static void main(String[] args)
 {
  Country india=new Country("India",1000);  
        Country japan=new Country("Japan",10000);  
            
        Country france=new Country("France",2000);  
        Country russia=new Country("Russia",20000);  
            
        Comparator<Country> comparator=new Comparator<Country>() {

   @Override
   public int compare(Country o1, Country o2) {
    return o2.getName().compareTo(o1.getName());
   }
  };
  
  System.out.println("Sorting TreeMap in reverse order of country name");
        TreeMap<Country, String> countryCapitalMap=new TreeMap<Country,String>(comparator);  
        countryCapitalMap.put(india,"Delhi");  
        countryCapitalMap.put(japan,"Tokyo");  
        countryCapitalMap.put(france,"Paris");  
        countryCapitalMap.put(russia,"Moscow");  
            
        Iterator<Country> countryCapitalIter=countryCapitalMap.keySet().iterator();//put debug point at this line  
        while(countryCapitalIter.hasNext())  
        {  
            Country countryObj=countryCapitalIter.next();  
            String capital=countryCapitalMap.get(countryObj);  
            System.out.println(countryObj.getName()+"----"+capital);  
            }  
        }  

}

When you run above program, you will get below output:
Sorting TreeMap in reverse order of country name
Russia----Moscow
Japan----Tokyo
India----Delhi
France----Paris

You can pass HashMap to constructor of TreeMap to sort it on Key

 TreeMap countryCapitalMap=new TreeMap(Map hm);

By passing HashMap to constructor of TreeMap, you can sort TreeMap.

Example: 
Create Country.java as below. It should implement Comparable interface

package org.arpit.java2blog;  
public class Country implements Comparable {  
  
 String name;  
 long population;  
   
 public Country(String name, long population) {  
  super();  
  this.name = name;  
  this.population = population;  
 }  
 public String getName() {  
  return name;  
 }  
 public void setName(String name) {  
  this.name = name;  
 }  
 public long getPopulation() {  
  return population;  
 }  
 public void setPopulation(long population) {  
  this.population = population;  
 }
@Override
public int compareTo(Object o) {
    Country country=(Country) o;
 return this.getName().compareTo(country.getName());
}  
       
}  

Create TreeMapCompMain.java as below:
package org.arpit.java2blog;

import java.util.HashMap;
import java.util.Iterator;
import java.util.TreeMap;

public class TreeMapCompMain {

 public static void main(String[] args)
 {
  Country india=new Country("India",1000);  
        Country japan=new Country("Japan",10000);  
            
        Country france=new Country("France",2000);  
        Country russia=new Country("Russia",20000);  
            
        HashMap<Country, String> countryCapitalMap=new HashMap<Country,String>();  
        countryCapitalMap.put(india,"Delhi");  
        countryCapitalMap.put(japan,"Tokyo");  
        countryCapitalMap.put(france,"Paris");  
        countryCapitalMap.put(russia,"Moscow");  
        
        System.out.println("Sorting HashMap by passing it to TreeMap constructor");
        TreeMap<Country,String> sortedTreeMapCountryCapital=new  TreeMap<Country,String> (countryCapitalMap);
        Iterator<Country> countryCapitalIter=sortedTreeMapCountryCapital.keySet().iterator();//put debug point at this line  
        while(countryCapitalIter.hasNext())  
        {  
            Country countryObj=countryCapitalIter.next();  
            String capital=countryCapitalMap.get(countryObj);  
            System.out.println(countryObj.getName()+"----"+capital);  
            }  
        }  

}

When you run program, you will get below output:
Sorting HashMap by passing it to TreeMap constructor
France----Paris
India----Delhi
Japan----Tokyo
Russia----Moscow


Written by Arpit:

If you have read the post and liked it. Please connect with me on Facebook | Twitter | Google Plus

 

Java tutorial for beginners Copyright © 2012