package Test; import java.util.HashMap; import java.util.Iterator; public class Test { public static void main(String[] args) { int a [] = {6,6,6,1,2,8,8,5,5,5,12}; int maxnum = 0; int maxvalue = 0; HashMap<Integer,Integer> map = new HashMap<Integer,Integer>(); HashMap<Integer,Integer> map2 = new HashMap<Integer,Integer>(); for(int i=0;i<a.length;i++) { int count = 0; for(int j=0;j<a.length;j++) { if(a[i]==a[j]) { count++; } } map.put(a[i], count);//map會把重複的數據過濾掉 } Iterator it = map.keySet().iterator(); Iterator it2 = map.keySet().iterator(); while(it.hasNext()) { Object key = it.next(); if(map.get(key)>maxnum) { maxnum = map.get(key); maxvalue = (Integer)key; } } map2.put(maxvalue, maxnum); while(it2.hasNext()) { Object key = it2.next(); if(map.get(key)==maxnum) { map2.put((Integer)key, maxnum); } } Iterator it3 = map2.keySet().iterator(); while(it3.hasNext()) { Object key = it3.next(); System.out.print("出現次數最多的數為:"+key+" "); System.out.println("出現次數:"+map2.get(key)); } } }