天天看點

統計單詞數量

統計每個單詞出現的次數
    有如下字元串"If you want to change your fate I think you must come to the dark horse to learn java"(用空格間隔)
    列印格式:
      to=3
      think=1
      you=2
      ...
           
public class HomeWork2 {
    public static void main(String[] args) {
        String str="If you want to change your fate I think you must come to the dark horse to learn java";
        String[] split = str.split(" ");
        Map<String,Integer> map=new HashMap<>();
        for (String s : split) {
            if (!map.containsKey(s)){
                map.put(s,1);
            }else {
                int integer = map.get(s);
                integer++;
                map.put(s,integer);
            }
        }
        for (Map.Entry<String,Integer>mm:map.entrySet()){
            String key = mm.getKey();
             int value = mm.getValue();
            System.out.println(key+"="+value);
        }
       /* Set<String> characters = map.keySet();
        for (String key : characters) {
            System.out.println(key + ":" + map.get(key));
        }*/
    }
}