1 import java.util.HashMap; 2 import java.util.Map; 3 import java.util.Random; 4 5 6 7 public class Test { 8 9 //String 可以为任意类型 也可以自定义类型 10 static Map<String, Integer> keyChanceMap = new HashMap<String,Integer>(); 11 static{ 12 keyChanceMap.put("出现比例为10的", 10); 13 keyChanceMap.put("出现比例为100的", 100); 14 keyChanceMap.put("出现比例为500的", 500); 15 keyChanceMap.put("出现比例为1000的", 1000); 16 keyChanceMap.put("出现比例为10000的", 10000); 17 } 18 19 public static void main(String[] args) { 20 Map<String, Integer> count = new HashMap<String,Integer>(); 21 for (int i = 0; i < 100000; i++) { 22 23 24 String item = chanceSelect(keyChanceMap); 25 26 if (count.containsKey(item)) { 27 count.put(item, count.get(item) + 1); 28 } else { 29 count.put(item, 1); 30 } 31 } 32 33 for(String id : count.keySet()){ 34 System.out.println(id+"\t出现了 "+count.get(id)+" 次"); 35 } 36 } 37 38 39 public static String chanceSelect(Map<String, Integer> keyChanceMap) { 40 if(keyChanceMap == null || keyChanceMap.size() == 0) 41 return null; 42 43 Integer sum = 0; 44 for (Integer value : keyChanceMap.values()) { 45 sum += value; 46 } 47 // 从1开始 48 Integer rand = new Random().nextInt(sum) + 1; 49 50 for (Map.Entry<String, Integer> entry : keyChanceMap.entrySet()) { 51 rand -= entry.getValue(); 52 // 选中 53 if (rand <= 0) { 54 String item = entry.getKey(); 55 return item; 56 } 57 } 58 59 return null; 60 } 61 }