你是否有遇到过这样的需求呢?假设有个用户表,然后你要在这个用户表里面随机抽取几个幸运用户出来,而且要保证不重复呢?有对吧,那么你幸运了,请接着往下看!!!
单个随机元素
1.使用Random.nextInt(int)方法
List<Integer> givenList = Arrays.asList(1, 2, 3,5,6,7,8,9,10);
Random rand = new Random();
int randomElement = givenList.get(rand.nextInt(givenList.size()));
2.使用Math.random()静态方法,然后乘以列表的大小,最后转成int类型的。
List<Integer> givenList = Arrays.asList(1, 2, 33,5,6,7,8,9,10);
int randomElement = givenList.get((int) (Math.random() * givenList.size()));
多线程环境
当在多线程环境下使用Randome实例的时候,
可能导致多个线程获取到相同值的情况,
这时我们可以使用ThreadLocalRandom类
int randomElementIndex
= ThreadLocalRandom.current().nextInt(listSize) % givenList.size();
2.选取随机的多个集合元素
有时候,你想获得随机的子列元素,可以使用Collections工具类
List<Integer> givenList = Arrays.asList(1, 2, 33,5,6,7,8,9,10);
Collections.shuffle(givenList);
int randomSeriesLength = 3;
List<Integer> randomSeries = givenList.subList(0, randomSeriesLength);
Java从集合中随机取出N个不重复的元素
/**
* 从集合中随机取出N个不重复的元素
* @param list 需要被取出数据的集合
* @param n 取出的元素数量
* @return
*/
private List<Integer> createRandoms(List<Integer> list, int n) {
Map<Integer,String> map = new HashMap();
List<Integer> news = new ArrayList();
if (list.size() <= n) {
return list;
} else {
while (map.size() < n) {
int random = (int)(Math.random() * list.size());
if (!map.containsKey(random)) {
map.put(random, "");
news.add(list.get(random));
}
}
return news;
}
}