Java Data Type How to - Count String to HashMap








Question

We would like to know how to count String to HashMap.

Answer

import java.util.HashMap;
import java.util.Map;
/*from w w  w  .  j  ava  2 s.  c  o  m*/
public class Main {
    static Map<String, Integer> count = new HashMap<String, Integer>();

    public static void main(String[] args) {
        addToCountMap("This is my test This is my test This is my test ");
        System.out.println(count);
    }

    private static void addToCountMap(String test) {
        String[] split = test.split(" ");
        for (String string : split) {
            if (!count.containsKey(string)) {
                count.put(string, 0);
            }
            count.put(string, count.get(string) + 1);
        }
    }
}

The code above generates the following result.