使用Map集合;定义一个泛型为String类型的List集合统计该集合中每个字符(注意,不是字符串)出现的次数。例如:集合中有”abc”、”bcd”两个元素,程序最终输出结果为:“a = 1,b = 2,c = 2,d = 1”。
public static void main(String[] args) {
ArrayList<String> list=new ArrayList();
HashMap<Character, Integer> map=new HashMap<Character,Integer>();
list.add("abc");
list.add("bcd");
list.add("abcdef");
for (int i = 0; i < list.size(); i++) {
String str =list.get(i);
char[] arr=str.toCharArray();
for (char c : arr) {
if(map.containsKey(c)){
int count=map.get(c);
count++;
map.put(c, count);
}else{
map.put(c, 1);
}
}
}
System.out.println(map);
}