權重隨機,利用TreeMap的ceilingKey方法:數組
/**
* 得到給定List集合裏權重大的結果
* @param list 元素是字符串數組,第一個是權重,第二個是須要加權重的字段
* @return
*/
public static String getRandom(List<String[]> list){
int total = 0;//總權重
//以權重區間段的後面的值做爲key存當前信息
TreeMap<Integer,String> map = new TreeMap<>();
for (String[] array : list) {
total += Integer.parseInt(array[0]);
map.put(total, array[1]);
}
int random = (int)(Math.random()*total) + 1;
Integer key = map.ceilingKey(random);
return map.get(key);
}
public static void main(String args[]) {
long start = System.currentTimeMillis();
String[] s1 = {"9", "1"};
String[] s2 = {"1", "2"};
List<String[]> list = Arrays.asList(s1, s2);
int t = 0;
for (int i=0; i < 10000000; i++) {
if ("2".equals(getRandom(list))) {
t++;
}
}
System.out.println("1000萬次耗時:" + (System.currentTimeMillis() - start));
//輸出命中2的次數
System.out.println(t);
}
複製代碼