查找一个数组中出现次数最多的数字以及它出现的次数并输出出来
public class FindMostAppearTime {
public static void getMostAppearNumber(int [] array){
HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();
int time = 0;
Map.Entry<Integer,Integer> maxEntry = null;
for(int i=0;i<array.length;i++){
if(map.get(array[i]) == null){
map.put(array[i],1);
}else{
map.put(array[i],1+(Integer)map.get(array[i]));
}
}
for(Map.Entry<Integer,Integer> entry:map.entrySet()){
if(entry.getValue()>time){
time = entry.getValue();
maxEntry = entry;
}
}
System.out.println("数组中出现次数最多的数字是="+maxEntry.getKey()+";出现的次数是:"+maxEntry.getValue());
}
public static void main(String[] args) {
int ar [] = {3,6,2,4,9,5,2,8,8,8,8,2};
getMostAppearNumber(ar);
}
}