场景: 随机生成50个10到50的数字。然后顺序输出每个数字出现的次数
实现原理: 使用TreeMap,默认带了顺序排序的功能
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); } }