今天看到一道編程題:給定數組String[] a = {"a","b","c","d","a","b","a","c","e"},查找數組中重複元素的個數:預期結果:a:3,b:2.編程
/**
* 查找數組裏的重複元素個數
*/
public static void findRepeatElementCount(String[] arrays){
Map<String,Integer> map = new HashMap<String,Integer>();
for(int i=0;i<arrays.length;i++){
if(map.get(arrays[i])!=null){
map.put(arrays[i],map.get(arrays[i])+1);
}else{
map.put(arrays[i],1);
}
}
//輸出值
Set<String> keys = map.keySet();
Iterator<String> its = keys.iterator();
while(its.hasNext()){
String key = its.next();
Integer value = map.get(key);
if(value>1){
System.out.println("元素"+key+" "+value);
}
}
}數組