java中用for循环求一个数组中出现最多次数的元素

如题所述

第1个回答  2015-08-19
// 测试数组
int[] array = {2,4,6,8,2,5,8,2,10};

HashMap<Integer, Integer> hashMap = new HashMap<Integer, Integer>();

for (int i : array) {
hashMap.put(i, hashMap.get(i) == null ? 0 :hashMap.get(i)+1);
}

Set<Integer> keySet = hashMap.keySet();

int maxKey = 0;
int maxValue = 0;

for (Integer integer : keySet) {
if(hashMap.get(integer) > maxValue){
maxKey = integer;
maxValue = hashMap.get(integer);
}
}

System.out.println(maxKey);

本回答被网友采纳