• 给定10万数据,数据范围[0~1000),统计出现次数最多的10个数据,并打印出现次数


    采用集合实现:

    import java.util.*;
    public class MapDemo {
        public static void main(String[] args) {
            Random random = new Random();
            int[] arr = new int[10];//存储出现数字前十的个数
            HashMap<Integer, Integer> hashMap = new HashMap<>();//统计各个数字出现的次数
            ArrayList<Integer> arrayList = new ArrayList<>();
            //统计每个数字出现的次数
            for (int i = 0; i < 100000; i++) {
                int num = random.nextInt(1000);
                if(hashMap.containsKey(num)){
                    hashMap.put(num,hashMap.get(num)+1);
                }else {
                    hashMap.put(num,1);
                }
            }
            for (Integer key:hashMap.keySet()
                 ) {
                arrayList.add(hashMap.get(key));
            }
    
            Comparator<Integer> comparator = new Comparator<Integer>() {
                @Override
                public int compare(Integer o1, Integer o2) {
                    return o2-o1;
                }
    
                @Override
                public boolean equals(Object obj) {
                    return false;
                }
            };
            Collections.sort(arrayList,comparator);
            for (int i = 0; i < 10; i++) {
                arr[i] = arrayList.get(i);
            }
            System.out.println("次数前十:"+Arrays.toString(arr));
            System.out.println("出现数字前十:");
            for (int i = 0; i < arr.length; i++) {
                for (Integer key:hashMap.keySet()) {
                    if(arr[i] == hashMap.get(key)){
                        System.out.println("数字:"+key+" "+"出现次数:"+hashMap.get(key));
                    }
                }
            }
    
        }
    
    }

    某次结果如图:

  • 相关阅读:
    pg常用命令
    dmhs
    Redis集群
    Redis哨兵高可用架构
    Redis外网无法连接的问题
    Redis主从
    Redis持久化
    Redis安装
    Mysql执行计划详解
    Mysql安装配置
  • 原文地址:https://www.cnblogs.com/128-cdy/p/12313325.html
Copyright © 2020-2023  润新知