代码:
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