1 public static void main(String[] args) { 2 // 学生选景点 a,b,c,d 四个景点,80个学生 3 String[] scene = {"A", "B", "C", "D"}; 4 StringBuilder sb = new StringBuilder(); 5 Random r = new Random(); 6 for (int i = 0; i < 80; i++) { 7 sb.append(scene[r.nextInt(scene.length)]); 8 } 9 System.out.println(sb); 10 11 // 定义一个集合统计 投票结果:A = x,B = x,C = x, 景点是键,值是投票数 12 Map<Character, Integer> info = new HashMap<>(); 13 14 // 遍历学生投票数 15 for (int i = 0; i < sb.length(); i++) { 16 // 提取当前选择景点的字符 17 char ch = sb.charAt(i); 18 // 判断map集合中键是否存在 19 if (info.containsKey(ch)){ 20 // 存在 计数 +1 21 info.put(ch,info.get(ch) + 1); 22 }else { 23 info.put(ch, 1); 24 } 25 } 26 // 输出集合 27 System.out.println(info); 28 }
标签:info,Map,ch,scene,投票,景点,集合,sb From: https://www.cnblogs.com/dsds/p/17985940