首页javamapJava Collection - 如何使用hashmap创建文本的字计数器

Java Collection - 如何使用hashmap创建文本的字计数器

我们想知道如何使用hashmap创建文本的字计数器。
import java.util.HashMap;
import java.util.Map;

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);
   }
}