static void ss() {
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
Integer[] nums = new Integer[500];// 定义一个长度500的整数组
Random ra = new Random();
// 循环给数组赋值(随机产生值)
for (int i = 0; i < nums.length; i++) {
nums[i] = ra.nextInt(50) + 1;// 1-50之间
}
Integer count = 0;// 出现的次数
for (int i = 0; i < nums.length; i++) {
if (nums[i] % 2 == 0) {
for (int j = 0; j < nums.length; j++) {
if (nums[i].equals(nums[j])) {
count++;
}
if (j == nums.length - 1) {// 最后赋值给map
map.put(nums[i], count);
count = 0;
}
}
}
}
System.out.println("排序前:" + map);
List<Map.Entry<Integer, Integer>> mappingList = null;
mappingList = new ArrayList<Map.Entry<Integer, Integer>>(map.entrySet());
Collections.sort(mappingList,
new Comparator<Map.Entry<Integer, Integer>>() {
public int compare(Map.Entry<Integer, Integer> mapping1,
Map.Entry<Integer, Integer> mapping2) {
// 降序或升序只需要更改参数位置
return mapping2.getValue().compareTo(
mapping1.getValue());
}
});
System.out.print("排序后:");
for (Map.Entry<Integer, Integer> mapping : mappingList) {
System.out.print(mapping.getKey() + ":" + mapping.getValue() + "\t");
}
String[] str = mappingList.get(0).toString().split("=");
System.out.println("\n出现次数最多的偶数:"+str[0]+",出现的次数为:"+str[1]);
}
温馨提示:内容为网友见解,仅供参考