定义一个泛型为String类型的List集合,统计该集合中每个字符(注意,不是字符串)出现的次数。例如:集合中有”abc”、”bcd”两个元素,程序最终输出结果为:“a = 1,b = 2,c = 2,d = 1”。
提示:
字符串可以转成字符数组 char[ ] chars=string.toCharArray();
保存每个字符的统计结果可以使用map
public static void work2() {
List<String> list = new ArrayList<>();
list.add("abc");
list.add("bcd");
Map<Character, Integer> map = new HashMap<>();//保存每个字符的统计结果
//统计个数
for (int i = 0; i < list.size(); i++) {
char[] chars = list.get(i).toCharArray();
for (char c : chars) {
int count = 1;
if (map.containsKey(c)) {
count = map.get(c) + count;
}
map.put(c, count);
}
}
//将最终统计结果展示在控制台
for (char key : map.keySet()) {
System.out.print(key + "=" + map.get(key) + " ");
}
}