Java进阶:集合进阶统计次数(双列集合HashMap && 单列集合Set):实现景点被选择的次数统计

~ 景点次数统计

     * 某个班级80名学生,现在需要组成秋游活动,
     * 班长提供了四个景点依次是(A,B, C, D),
     * 每个学生只能选择一个景点,请统计出最终那个景点想去的人数最多
     */
  • 代码示例:
    public static void main(String[] LiuJinTao) {
        // 1. 生成景点,用来被选择
        String[] arr = {"A", "B", "C", "D"};


        ArrayList<String> list = new ArrayList<>();

        // 2. 80 名学生对景点进行投票
        Random r = new Random();
        for (int i = 0; i < 80; i++) {
            int randomIndex = r.nextInt(arr.length);
            list.add(arr[randomIndex]);
        }

        System.out.println(list);
        // 3. 创建 Map集合存储景点和被选次数
        HashMap<String, Integer> hm = new HashMap<>();
        for (String name : list) {
            // 1.判断当前景点是否存在 Map 集合中
            if (hm.containsKey(name)) {
                // 2.存在 得到次数添加一次
                int count = hm.get(name);
                count++;
                // 3.将新的次数重新覆盖(达到累加效果)
                hm.put(name, count);
            } else  {
                // 不存在 添加
                hm.put(name, 1);
            }
        }
        System.out.println(hm);


        // 4. 得到最大次数
        int max = 0;

        // 5. 遍历集合得到每个景点被选择的次数 (键值对遍历 Map 双列集合)
        Set<Map.Entry<String, Integer>> entry = hm.entrySet();      // entrySet() 方法得到键值对对象 存入单列集合中
        for (Map.Entry<String, Integer> stringIntegerEntry : entry) {
            // 通过 Set集合中的 get 方法获取键值对数据
            if (stringIntegerEntry.getValue() > max) {
                // 当景点的选择次数 大于 max   则交换赋值
                max = stringIntegerEntry.getValue();
            }
        }
        System.out.println(max);

        // 6. 判断景点被选的最多次数
        for (Map.Entry<String, Integer> ifMax : entry) {
            if (ifMax.getValue() == max) {
                System.out.println("票数最多的景点为: " + ifMax.getKey() + ":" + hm.get(ifMax.getKey()) + "票");
            }
        }
    }

你可能感兴趣的:(Java中的小常识,java,python,开发语言)