代码:
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 TreeMap<>((o1, o2) -> o2 - o1);
// 遍历数组
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);
}
}
// 遍历数据
Set<Map.Entry<Integer, Integer>> entries = map.entrySet();
for (Map.Entry<Integer, Integer> entry : entries) {
System.out.println(entry.getKey() + ":" + entry.getValue());
}
}
}
结果:
51:1
45:1
31:1
21:1
12:2
11:1
8:1
7:1
6:2
4:4
3:3
2:1
1:3
拓展:
题目:有一个数组[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/106097969