怎么从一个数组中找出重复最多的元素,并统计重复个数

如题所述

public static void main(String[] args) {
int array[]={5, 10, 10, 5, 2, 5, 3, 5, 10, 5, 2, 5, 5, 10, 1, 5, 1};
Arrays.sort(array);// 给数组排序
int count=0;
int tmp=array[0];
Map map=new HashMap();
for(int i=0; i < array.length; i++) {
if(tmp != array[i]) {
tmp=array[i];
count=1;
} else {
count++;
}
map.put(array[i], count);
}
map=sortByValue(map);
Set<Integer> key = map.keySet();
for (Iterator it = key.iterator(); it.hasNext();) {
Integer s = (Integer) it.next();
System.out.println(s+"出现了"+map.get(s));
}
}

public static Map sortByValue(Map map) {
List list=new LinkedList(map.entrySet());
Collections.sort(list, new Comparator() {
// 将链表按照值得从小到大进行排序
public int compare(Object o1, Object o2) {
return ((Comparable)((Map.Entry)(o2)).getValue()).compareTo(((Map.Entry)(o1)).getValue());
}
});
Map result=new LinkedHashMap();
for(Iterator it=list.iterator(); it.hasNext();) {
Map.Entry entry=(Map.Entry)it.next();
result.put(entry.getKey(), entry.getValue());
}
return result;
}
温馨提示:答案为网友推荐,仅供参考

相关了解……

你可能感兴趣的内容

本站内容来自于网友发表,不代表本站立场,仅表示其个人看法,不对其真实性、正确性、有效性作任何的担保
相关事宜请发邮件给我们
© 非常风气网