效果如下:
package cn.edu.nuc.map;
import java.util.HashMap;
import java.util.Map;
public class Test2 {
/**
* 统计字符串中字符出现的次数
* 1.对字符串进行切割
* 2.遍历字符串
* 3.创建map对象,通过字符查看map中是否含有该字符
* 若有该字符,value++;否则,添加该字符,设置value为1
* 4.遍历map 查看统计结果
* @param args
*/
public static void main(String[] args) {
String str="hello tom hello jerry hello tom hello jiji hello tom";
String[] strings = str.split("\\s");
/**
* 方法一 用getOrDefault来设置map
*/
Map<String,Integer> map2 = new HashMap();
for (String string : strings) {
Integer integer = map2.getOrDefault(string, 0);
integer++;
map2.put(string, integer);
}
for (String string : map2.keySet()) {
System.out.println(string+" "+map2.get(string));
}
System.out.println("------------------------------------------");
/**
* 方法二 if-else创建
*/
Map<String,Integer> map1 = new HashMap();
for (String string : strings) {
Integer integer = map1.get(string);
if(integer==null)
map1.put(string,1);
else {
integer=integer+1;
map1.put(string,integer);
}
}
for (String string : map1.keySet()) {
System.out.println(string+" "+map1.get(string));
}
}
}