package zuoye11;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
//统计单词出现的次数
public class Demo01 {
public static void main(String[] args) {
String str = "if you want to change your fate I think you must to learn java";
String[] aa = str.split(" +");//拆分字符串并存入数组aa
//System.out.println(Arrays.toString(aa));
Map<String, Integer> map = new HashMap<>();//定义一个HashMap
//System.out.println(map.containsKey("aa"));
for(String s:aa) {//遍历数组aa
if(map.containsKey(s)) {//如果存在key = s
map.put(s, map.get(s)+1);//覆盖key values+1
}else {
map.put(s, 1);//不存在直接添加
}
}
//System.out.println(map);
for(Map.Entry<String, Integer> et: map.entrySet()) {//遍历集合map
System.out.println(et.getKey()+"="+et.getValue());
}
}
}
利用HashMap统计单词出现的次数
最新推荐文章于 2022-11-15 19:30:44 发布