【Algorithm Problem】统计文章中每个单词出现的次数

Posted by 西维蜀黍 on 2019-05-14, Last Modified on 2022-12-10

Solution

String[] strs = {"apple",...};
Map<String, Integer> map = new HashMap<String, Integer>();
for (String str : strs) {
    if (map.containsKey(str)) {
        Integer integer = map.get(str);
        integer++;
        map.put(str, integer);
    } else {
        map.put(str, 1);
    }
}

for (Map.Entry<String, Integer> me : map.entrySet()) {
    String strKey = me.getKey();
    Integer iCount = me.getValue();
    System.out.println(strKey + "出现了" + iCount + "次");
}

TOC