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

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

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--;
            }
        }
    }

Guess you like

Origin blog.csdn.net/a1099380657/article/details/120758307