Home  >  Core Java

java.util.TreeMap Java Example

By Arvind Rai, August 24, 2013
java.util.TreeMap implements sorted Map. Sorting is done on key as natural ordering. Comaparator can also be provided to sort according to our requirements. TreeMap uses Red-Black tree algorithm to sort the content. For the large data in TreeMap, the functions like get, put, containsKey, containsValue, remove will work fast with better performance. TreeMap is not synchronized. We can synchronize it by using
SortedMap m = Collections.synchronizedSortedMap(new TreeMap()); 
 
Find the example below.

Natural Sorting of TreeMap on the basis of Key

TreeMapDemo.java
package com.concretepage.util;
import java.util.Map.Entry;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;
public class TreeMapDemo {
    public static void main(String[] args) {
        SortedMap<Integer,String> map = new TreeMap<Integer, String>();
        map.put(1,"A");
        map.put(3,"C"); 
        map.put(2,"B");
       
        Set<Entry<Integer,String>> ob= map.entrySet();
        for(Entry<Integer,String> en : ob){
            System.out.print(en.getKey());
            System.out.println(en.getValue());
        }
    }
}
 
Output
1A
2B
3C

Sorting of TreeMap for a given Comparator

TreeMapDemo.java
package com.concretepage.util;
import java.util.Comparator;
import java.util.Map.Entry;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;
public class TreeMapDemo {
    public static void main(String[] args) {
        SortedMap<Bean,String> map = new TreeMap<Bean,String>(new A());
        map.put(new Bean("A"),"Ram");
        map.put(new Bean("C"),"Shyam"); 
        map.put(new Bean("B"),"Rahul");
        Set<Entry<Bean,String>> ob= map.entrySet();
        for(Entry<Bean,String> en : ob){
            System.out.print(en.getKey().name);
            System.out.print("-");
            System.out.println(en.getValue());
        }
    }
}
class A implements Comparator<Bean> {

    @Override
    public int compare(Bean b1, Bean b2) {
      return b1.name.compareTo(b2.name);
    }
}
class Bean {
    public String name;

    public Bean(String name) {
        this.name = name;
    }
}
 
Output
A-Ram
B-Rahul
C-Shyam
POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS






©2019 concretepage.com | Privacy Policy | Contact Us