采用集合实现:
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)); } } } } }
某次结果如图: