Java Collection How to - Create word counter of text using hashmap








Question

We would like to know how to create word counter of text using hashmap.

Answer

import java.util.HashMap;
import java.util.Map;
//from  w w w. j ava 2 s. c  o m
public class Main {
  public static void main(String args[])
   {
      
      String s = "this is a test this is a test";
      String[] splitted = s.split(" ");
      Map<String, Integer> hm = new HashMap<String, Integer>();

      for (int i=0; i<splitted.length ; i++) {
         if (hm.containsKey(splitted[i])) {
            int cont = hm.get(splitted[i]);
            hm.put(splitted[i], cont + 1);
         } else {
            hm.put(splitted[i], 1);
         }
      }
      System.out.println(hm);
   }
}

The code above generates the following result.