使用Map統計隨機數出現的次數
題:統計隨機數字出現的次數,以及出現次數最多的數字和次數分別是多少?
解答:
使用Map不可存儲相同鍵的屬性來統計,如果在Map中沒有出現該數字,那麼它出現的次數就爲1;如果在Map中已經存在該數字,那麼把該值出現的次數+1
import java.util.*;
public class MapCountWords {
public static void main(String[] args) {
/**
* 統計隨機數字出現的次數,以及出現次數最多的次數是多少?
*/
TreeMap<Integer,Integer> map = new TreeMap();
for (int i = 0; i < 50; i++) {
int num = (int) (Math.random() * 40 + 10);
//如果該值在map中沒有出現,則出現次數爲1
if (map.get(new Integer(num)) == null) {
map.put(new Integer(num), 1);
} else {
//如果該值在map中存在,則把出現次數+1
map.put(num, ((Integer)map.get(num)).intValue()+1);
}
}
for (Map.Entry<Integer,Integer> entry : map.entrySet()){
System.out.println(entry);
}
//計算最大的次數
Collection collect = map.values();
Integer max = (Integer) Collections.max(collect);
System.out.println("出現最多次數爲:" + max);
}
}