Apr 13, 2012

TreeMap Class

public class TreeMap extends AbstractMap implements SortedMap, Cloneable,Serializable
The TreeMap class implements the SortedMap interface (and thus the Map interface too), but stores elements in a tree structure. The treeMap returns keys in sorted order.

Constructory
TreeMap() Constructs a new, empty map, sorted according to the keys' natural order
TreeMap(Comparator c) Constructs a new, empty map, sorted according to the given comparator.
TreeMap(Map m) Constructs a new map containing the same mappings as the given map, sorted according to the keys' natural order.
TreeMap(SortedMap m) Constructs a new map containing the same mappings as the given SortedMap, sorted according to the same ordering.



Some Important Methods
Object
firstKey() Returns the first (lowest) key currently in this sorted map.
SortedMap
headMap(Object toKey) Returns a view of the portion of this map whose keys are strictly less than toKey.
Object
lastKey() Returns the last (highest) key currently in this sorted map.
SortedMap
tailMap(Object fromKey) Returns a view of the portion of this map whose keys are greater than or equal to fromKey.


Example:
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
public class TreeMapDemo
{
   public static void main(String[] args)
  {
     if(args.length < 1)
     {
        System.out.println("Usage : java WordsCount <sample string>");
        System.exit(0);
     }
     Map WordList = new HashMap();
     for(int count = 0;count < args.length; count++)
     {
        // Get the next word
        String key = args[count];
        // Get the frequency of the word
        // referred by "key"
        Integer frequency = (Integer)WordList.get(key);
        /* If the word does not exists in the map
then initialize frequency to 1
else increment it by 1
*/
        if(frequency == null)
        {
           frequency = new Integer(1);
        }
        else
        {
           int value = frequency.intValue();
           frequency = new Integer(value + 1);
        }
        // Update the frequency for the word
        // referred by "key"
        WordList.put(key, frequency);
     }
     // Display the words and its
     // corresponding frequency
     Map sortedWordList = new TreeMap(WordList);
     System.out.println(sortedWordList);
   }
} 

0 comments :

Post a Comment