Any fool can write code that a computer can understand. Good programmers write code that humans can understand. Martin Fowler

TreeMap

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

0 Comments


Definition

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

Character

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

								
package com.careerdrill.collections.map;

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());
	}

}
						

Output

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

Comparison

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.

0 Comments



Please login to add comments.