题目:有一个数组[1,3,4,1,4,6,3,1,11,31,2,45,12,4,6,7,8,21,12,3,4,51],请统计数组中每个数字出现的次数,并且按照次数从大到小打印这些数字和次数

代码:

public class Test {
    public static void main(String[] args) {
        // 测试数据
        int[] arrays = {1, 3, 4, 1, 4, 6, 3, 1, 11, 31, 2, 45, 12, 4, 6, 7, 8, 21, 12, 3, 4, 51};

        // map的key是上述数组中的数字,value是数字在上述数组中出现的数目
        Map<Integer, Integer> map = new HashMap<>();

        // 遍历数组
        for (int num : arrays) {
            // 检查该数字是否已经放入了map
            if (map.containsKey(num)) {
                // 如果已经放入了map,那就让value+1之后在放入一次,用以覆盖掉里面原有的key和value
                map.put(num, map.get(num) + 1);
            } else {
                // 如果没有放入,那就放入一次,由于是首次放入,那value肯定是1
                map.put(num, 1);
            }
        }

        // 把Map集合按照value倒叙排序
        List<Map.Entry<Integer, Integer>> list = new ArrayList<>(map.entrySet());
        Collections.sort(list, (o1, o2) -> o2.getValue() - o1.getValue());

        // 使用迭代器把所有的内容遍历出来
        Iterator<Map.Entry<Integer, Integer>> iterator = list.iterator();
        while (iterator.hasNext()) {
            Map.Entry<Integer, Integer> entry = iterator.next();
            Integer key = entry.getKey();
            Integer value = entry.getValue();
            System.out.println("数字" + key + "次数:" + value);
        }
    }
}

结果:

数字4次数:4
数字1次数:3
数字3次数:3
数字6次数:2
数字12次数:2
数字2次数:1
数字7次数:1
数字8次数:1
数字11次数:1
数字45次数:1
数字51次数:1
数字21次数:1
数字31次数:1

拓展:

题目:有一个数组[1,3,4,1,4,6,3,1,11,31,2,45,12,4,6,7,8,21,12,3,4,51],请统计数组中每个数字出现的次数,并且按照数字从大到小打印这些数字和次数:https://blog.csdn.net/qq_42449963/article/details/107204408

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值