java.util.TreeMap Java Example
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());
Natural Sorting of TreeMap on the basis of Key
TreeMapDemo.javapackage 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()); } } }
1A 2B 3C
Sorting of TreeMap for a given Comparator
TreeMapDemo.javapackage 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; } }
A-Ram B-Rahul C-Shyam