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 countryCapitalMap=new TreeMap();
        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 comparator=new Comparator() {

            @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 countryCapitalMap=new TreeMap(comparator);  
        countryCapitalMap.put(india,"Delhi");  
        countryCapitalMap.put(japan,"Tokyo");  
        countryCapitalMap.put(france,"Paris");  
        countryCapitalMap.put(russia,"Moscow");  

        Iterator 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 countryCapitalMap=new HashMap();  
        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 sortedTreeMapCountryCapital=new  TreeMap (countryCapitalMap);
        Iterator 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
[social_share share_on="facebook,twitter,linkedin,whatsapp"][post_navigator in_same_term="true"]

Leave a Reply

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

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.