记录项目中遇到的随机抽取模块的核心代码
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 newList=new ArrayList(); int temp=0; if (count != 0) { for(int i=0;i<Math.ceil(count);i++){ temp=random.nextInt(listData.size()); if(!tempList.contains(temp)){ tempList.add(temp); newList.add(listData.get(temp)); } else{ i--; } } }
|

-———————————————-
发现了个新的方法,比上面的随机简单,直接打乱原有的 list 顺序,再取出来
1 2 3 4 5 6
| Collections.shuffle(listData);
for (int i = 0; i < count; i++) { newList.add(listData.get(i)); }
|