Java 怎么算一组array中每个数字出现的次数, 如果某个数字出现次数是最多的,就输出这个数,

Java 怎么算一组array中每个数字出现的次数, 如果某个数字出现次数是最多的,就输出这个数,如果有和它出现次数一样都是最多的就输出-1

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; }
温馨提示:答案为网友推荐,仅供参考