Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it. Brian Kernighan


Language Java | Level Intermediate | Category Java collections framework (JCF) | 2015-07-22 23:36:24



Treemap is red block tree based tree which sort the elements according to the natural ordering or comparator interface implementation class.


Red-Black tree based NavigableMap implementation.
It supports natural ordering or implement Comparator interface.
It does not synchronize.
The fail-fast behavior of iterators should be used only to detect bugs.
It throws ConcurrentModificationException when multiple threads access the object.

source Code


import java.util.Arrays;
import java.util.Map;
import java.util.TreeMap;

public class TreeMapUse {

	public static void main(String[] args) {
		String []strarray = {"CPP","Java","CSharp","Perl"};
		System.out.println("Array of items to add in Treemap: " + Arrays.toString(strarray));
		Map< Integer, String > integerMap = new TreeMap< Integer, String >();
		for(int i = 0; i < strarray.length ; i++)
			integerMap.put(i+1, strarray[i]);

        System.out.println("Itmes in the Treemap : "+ integerMap.toString());



Array of items to add in Treemap: [CPP, Java, CSharp, Perl]
Items in the Treemap : {1=CPP, 2=Java, 3=CSharp, 4=Perl}


Hashmap LinkedHashmap Treemap
Hashmap does not maintain any order. LinkedHashmap maintains insertion order. Treemap provides natural sorting.
LinkedHashmap and Hashmap allow null. LinkedHashmap and Hashmap allow null. Treemap does not allow null.
O(n) O(1) O(logn)
Implemented based on buckets. Maintaining insertion order using double buckets. Internally implement based on red block tree.
Compare using equals() and hashCode() methods. Compare using equals() and hashCode() methods. Comparable or comparator interface implementation.

When to use

When you want to sort elements using Comparator implementation or natural sorting, you can use TreeMap.


Please login to add comments.