问题描述
> 给定一个字符串数组,数组中内容中有重复,先打印各数组中字符出现的字数
> 使用hashMap来设计,hashMap的键存放字符串,值统计出现的次数
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
public class Dem06 {
/**
* 给定一个字符串数组,数组中内容中有重复,先打印各数组中字符出现的字数
* 使用hashMap来设计,hashMap的键存放字符串,值统计出现的次数
* @param args
*/
public static void main(String[] args) {
String []strs = {"张三","李四","王五","张三","李四","张三"};
AccountUtil.printMap(AccountUtil.account(strs));
}
}
class AccountUtil{
/**
* 统计出现次数
* @param strs
* @return
*/
public static Map<String, Integer>account(String []strs){
Map<String,Integer> map = new HashMap<>();
for(int i=0;i<strs.length;i++) {
//方法一
// String str = strs[i];//首先取出第一个数
// if(map.get(str) == null) {//如果取出的数之前没有取到则设置次数为1
// map.put(str, 1);
// }else {
// map.put(str, map.get(str)+1);//否则,第二次取到这个字符在前面的基础上加1
// }
//方法二
if(map.containsKey(strs[i])) {
map.put(strs[i], map.get(strs[i])+1);
}else {
map.put(strs[i], 1);
}
}
return map;
}
/**
* 打印
* @param map
*/
public static void printMap(Map<String, Integer> map) {
Set<Entry<String, Integer>> entrys = map.entrySet();
for(Entry<String, Integer>entry:entrys) {
System.out.println(entry.getKey()+"出现的次数"+entry.getValue());
}
}
}
运行结果
李四出现的次数2
张三出现的次数3
王五出现的次数1