测试:
import java.util.HashMap;
import java.util.Map;
//单词频度统计
public class test {
public static void main(String[] args) {
String s = "To drive is without a license is illegal. It is illegal to drive without a license.Driving without a license is illegal.";
//单词分割 resplace替换 toLowerCase将大写字母变为小写
s = s.replace(".", " ").replace(",", " ").toLowerCase();
//split分割 \\s+一个或多个空格
String[] strs = s.split("\\s+");
Map<String, Integer> map = new HashMap<>();//键值对
//添加到Map
for (String ss : strs) {
if (map.containsKey(ss)) {
map.put(ss, map.get(ss) + 1);
} else {
map.put(ss, 1);
}
}
//遍历Map输出
for (String key : map.keySet()) {
System.out.println(key + ":" + map.get(key));
}
}
}
运行: