学习了HashMap的基本用法。
做了道题练习一下,随机产生50个10到50的数字,统计每个数字出现次数。按照数字的升序打印
- package map;
- import java.util.HashMap;
- import java.util.Iterator;
- import java.util.Random;
- import java.util.TreeSet;
- public class HomeWork {
- public static void main(String[] args) {
- Random generator = new Random();
- int i = 0;
- TreeSet<Integer> ts = new TreeSet<Integer>();
- HashMap<Integer, Integer> hm = new HashMap<Integer, Integer>();
- while (i < 50) {
- Integer key = new Integer(generator.nextInt(41) + 10);
- ts.add(key);
- if (hm.containsKey(key)) {
- Integer tmp = hm.get(key);
- hm.put(key, new Integer(tmp.intValue() + 1));
- } else {
- hm.put(key, new Integer(1));
- }
- i++;
- }
- // display
- int max_value = 0;
- Integer max_key = null;
- for (Iterator<Integer> iter = ts.iterator(); iter.hasNext();) {
- Integer tmp = iter.next();
- Integer value = hm.get(tmp);
- if (value.intValue() > max_value) {
- max_value = value.intValue();
- max_key = tmp;
- }
- System.out.println(tmp + " : " + value);
- }
- System.out.println("Max key is " + max_key + " max value associed is "
- + max_value);
- }
- }
阅读(534) | 评论(0) | 转发(0) |