Thursday, August 18, 2016

TreeMap Quick Reference

·         TreeMap object is sorted according to the natural ordering of its keys if created using default constructor( new TreeMap()), or by a  Comparator if TreeMap object is created by passing Comparator to  constructor ( new TreeMap(comparator))
·          Provides guaranteed log(n) time cost for the containsKey, get, put and remove operations.
·         If TreeMap object is created using default constructor then all keys inserted into the map must implement the Comparable interface else you will get exception while adding key-values to TreeMap instance.
java.lang.ClassCastException: xxxx cannot be cast to java.lang.Comparable
·         All keys inserted into the map must be of same type. e.g. you can’t add integer as a key into a map whose keys are String
·         Does not allows null keys, valuse can be null.
·         A TreeMap is not synchronized. Means its methods are not synchronized.
·         In multi-threaded environment, to prevent accidental unsynchronized access to the TreeMap that can modify it, wrap TreeMap using Collections.synchronizedSortedMap method
               SortedMap m = Collections.synchronizedSortedMap(new TreeMap(...));
·         The iterators returned by this class's iterator methods are fail-fast. If the map is modified at any time after the iterator is created, in any way except through the iterator's own remove method, the iterator will throw a ConcurrentModificationException.
·         Fail-fast iterators throw ConcurrentModificationException on a best-effort basis. But one must not write program that depends on this behaviour.

·         There are multiple ways to iterate over TreeMap

//create TreeMap instance
    TreeMap treeMap = new TreeMap();

    //add key value pairs to TreeMap
    treeMap.put("1","A");
    treeMap.put("2","B");
    treeMap.put("3","C");

1. Iterator using Collection values() - only iterate TreeMap's values

Collection c = treeMap.values();
Iterator itr = c.iterator();
while(itr.hasNext())
      System.out.println(itr.next());

2. Iterator using entrySet() - iterate TreeMap's keys and values in map form

for (Map.Entry entry : treeMap.entrySet()) {
        V value = entry.getValue();
        K key = entry.getKey();
   }

3. Iterator using keySet() - iterate TreeMap's keys which can be used to get values

Set keys = map.keySet();
   for (Iterator i = keys.iterator(); i.hasNext();) {
     Integer key = (Integer) i.next();
     String value = (String) map.get(key);
   }

Note : If the TreeMap is modified while an iteration over the collection/set is in progress (except through the iterator's own remove operation, the results of the iteration are undefined.The collection/set supports element removal, which removes the corresponding mapping from the map, via the Iterator.remove, Set.remove, removeAll, retainAll, and clear operations.  It does not support the add or addAll operations.


·         put(K key, V value) method returns previous value associated with key, or null if there was no mapping for key. If the map previously contained a mapping for the key, the old value is replaced with new value.

Total Pageviews