Pages

Thursday, August 30, 2012

Linked HashMap

If you need a HashMap which will persist the insertion order, you need to use Linked HashMap.

An example which will display unique  word and the word count  in  a String persisting the insertion order.

""The dog went to the dog park"


 void wordCount(String string)
{
LinkedHashMap map = new LinkedHashMap();
String[] words = string.split(" ");

for(int i = 0; i < words.length; i++)
{
       
        if(!map.containsKey(words[i].toLowerCase()))
        {
            map.put(words[i].toLowerCase(), 1);  
        }
        else
        {
            int count = (Integer) map.get(words[i]);
            map.put(words[i], ++count);
        }
    }
 
Iterator> it = map.entrySet().iterator();
Map.Entry pairs = null;
while(it.hasNext())
{
         pairs = (Map.Entry)it.next();
System.out.println(new      StringBuffer(pairs.getKey().toString()).append(" ").append(pairs.getValue().toString()).toString());
}
 
 
}


This will give you


the 2
dog 2
went 1
to 1
park 1


No comments: