java在list随中机抽取任意数目

记录项目中遇到的随机抽取模块的核心代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
List<Info> listData = InfoService.listByPage(Info,pageParameter);

if (count >= listData.size) {
result.setMsg("筛选数超过总数");
result.setSuccess(false);
} else {
Random random=new Random();
List<Integer> tempList=new ArrayList<Integer>();//临时存放产生的list索引,去除重复的索引
List newList=new ArrayList();//生成新的list集合
int temp=0;
if (count != 0) {
for(int i=0;i<Math.ceil(count);i++){
temp=random.nextInt(listData.size());//初始化一个随机数,将产生的随机数作为被抽list的索引
if(!tempList.contains(temp)){//判断随机抽取的随机数
tempList.add(temp);
newList.add(listData.get(temp));
}
else{
i--;
}
}
}

点击并拖拽以移动

-———————————————-

发现了个新的方法,比上面的随机简单,直接打乱原有的 list 顺序,再取出来

1
2
3
4
5
6
//打乱顺序
Collections.shuffle(listData);
//取出 count 数量的专家
for (int i = 0; i < count; i++) {
newList.add(listData.get(i));
}