fork download
  1. import java.util.*;
  2. /**
  3.  * Count frequency of words occurring in a string
  4.  */
  5. class MapExample {
  6. public static void main(String[] args){
  7. String str = "hello world how are you how is life i am into ascent";
  8. String[] strr = str.split("\\s");
  9. workMap(strr);
  10. }
  11.  
  12. static void workMap(String...words){
  13. Map map = new HashMap();
  14. Integer ONE = new Integer(1);
  15.  
  16. for(String word : words){
  17. Integer frequency = (Integer)map.get(word);
  18. /*
  19.   'frequency' is the count of the words.
  20.   For a new word getting added to the Map, we set its frequency as 1.
  21.   For existing words, we take their existing frequency (value in the map)
  22.   and increment it and put back into the map correspondint to that word (key in the map)
  23.   */
  24. frequency = (frequency == null) ? ONE : new Integer(frequency.intValue() + 1);
  25. map.put(word, frequency);
  26. }
  27. System.out.println("Unsorted:");
  28. System.out.println(map);
  29.  
  30. Map sortedMap = new TreeMap(map);
  31. System.out.println("Sorted:");
  32. System.out.println(sortedMap);
  33. }
  34. }
  35.  
Success #stdin #stdout 0.08s 380160KB
stdin
Standard input is empty
stdout
Unsorted:
{hello=1, is=1, life=1, are=1, how=2, am=1, into=1, you=1, ascent=1, world=1, i=1}
Sorted:
{am=1, are=1, ascent=1, hello=1, how=2, i=1, into=1, is=1, life=1, world=1, you=1}