编写java程序,统计某个数组中每个单词出现的次数
public static void main(String[] args) {
String[] arr = {"ab","ab","ab","ac","ab","ac","ds","sdf","sdf","sdf","sdf","sdf","sdf","sdf"};
//创建map key保存字符串 value 保存出现的次数
Map<String,Integer> map = new HashMap<String, Integer>();
for (int i = 0; i < arr.length; i++) {//循环数组
if(map.containsKey(arr[i])){//判断如果key中已存在该字符串
map.put(arr[i], map.get(arr[i])+1);//value值 加一次(多出现一次)
}else{
map.put(arr[i], 1);//如果该字符串没有出现 map新保存一组数据 出现次数为1次
}
}
//循环结束
//迭代map
Set<String> set = map.keySet();
Iterator<String> it = set.iterator();//iterator迭代器
while (it.hasNext()) {
String key = (String) it.next();
System.out.println(key+"出现的次数为"+" "+map.get(key)+"次");
}
}
控制台输出结果
想要具体的程序,急!!!
已经有人给出了
2016-07-04
public static void main(String[] args) {
String[] arr = {"ab","ab","ab","ac","ab","ac","ds","sdf","sdf","sdf","sdf","sdf","sdf","sdf"};
//创建map key保存字符串 value 保存出现的次数
Map<String,Integer> map = new HashMap<String, Integer>();
for (int i = 0; i < arr.length; i++) {//循环数组
if(map.containsKey(arr[i])){//判断如果key中已存在该字符串
map.put(arr[i], map.get(arr[i])+1);//value值 加一次(多出现一次)
}else{
map.put(arr[i], 1);//如果该字符串没有出现 map新保存一组数据 出现次数为1次
}
}
//循环结束
//迭代map
Set<String> set = map.keySet();
Iterator<String> it = set.iterator();//iterator迭代器
while (it.hasNext()) {
String key = (String) it.next();
System.out.println(key+"出现的次数为"+" "+map.get(key)+"次");
}
}
控制台输出结果
Set<String> keys = map.keySet();
for (String key : keys) {
System.out.println(key+"="+map.get(key));
}
foreach遍历即可