思路:
先將數(shù)組中的元素存放在hashmap中,其中key是元素,value是出現(xiàn)的次數(shù),在添加之前判斷hashmap中是否已經(jīng)包含了該元素,如果包含了將value+1,如果沒(méi)有的話(huà)直接放在hashmap中
private static void getNumberOfCount(int[] array) {
if (array == null || array.length <= 0) {
return;
}
HashMap<Integer, Integer> hashMap = new HashMap<>();
for (int i = 0; i < array.length; i++) {
if (hashMap.containsKey(array[i])) {------->添加之前先判斷,如果存在了value+1
hashMap.put(array[i], hashMap.get(array[i]) + 1);
} else {
hashMap.put(array[i], 1);----->將元素放在hashmap中
}
}
//得到map中所有的鍵
Set<Integer> keyset = hashMap.keySet();
//創(chuàng)建set集合的迭代器
Iterator<Integer> it = keyset.iterator();
while (it.hasNext()) {
Integer key = it.next();
Integer value = hashMap.get(key);
System.out.println(key + "--total==" + value + "count");
}
}