場景: 隨機生成50個10到50的數字。而後順序輸出每一個數字出現的次數java
實現原理: 使用TreeMap,默認帶了順序排序的功能dom
public static void main(String[] args) { Map map = new TreeMap(); Random random = new Random(); for(int i = 0; i < 50; i++){ int number = random.nextInt(41) +10; Integer in = new Integer(number); if(map.get(in) == null){ map.put(in, new Integer(1)); }else { int value = ((Integer)map.get(in)).intValue(); map.put(in, new Integer(value +1)); } } Set set = map.keySet(); Iterator iter = set.iterator(); while (iter.hasNext()) { Integer key = (Integer)iter.next(); Integer value = (Integer)map.get(key); System.out.println(key + "=" + value); } }