龙哥网

龙哥网

java 获取集合中随机个数不重复项,返回新集合或者项在原集合的下标数组
2021-12-18

1、获取集合中随机个数不重复的项,组成一个新的子集

 Java
/**
 * 获取集合中随机个数不重复的项,组合新的集合
 * @param list 数据列表
 * @param num 随机数量
 * @return 子集
 */public static List getRandomListByNum(List list,int num){
    List sourceList = new ArrayList(list);
    List targetList = new ArrayList();
    if(num >= list.size()){
        return list;
    }
    // 创建随机数
    Random random = new Random();
    // 根据数量遍历
    for(int i=0; i<num; i++){
        // 获取源集合的长度的随机数
        Integer index = random.nextInt(sourceList.size());
        // 获取随机数下标对应的值
        targetList.add(sourceList.get(index));
        // 删除数据
        sourceList.remove(sourceList.get(index));
    }
    return targetList;}


2、获取集合中随机个数不重复的项,获取这些项在原集合中的下标

 Java
/**
 * 获取集合中随机个数不重复的项,返回下标数组
 * @param list 数据列表
 * @param num 随机数量
 * @return 子集
 */public static List<Integer> getRandomIndexListByNum(List list,int num){
    List targetList = new ArrayList();
    List<Integer> indexList = new ArrayList<Integer>();
    if(num >= list.size()){
        return list;
    }
    // 创建随机数
    Random random = new Random();
    // 当set长度不足 指定数量时
    while (targetList.size() < num) {
        // 获取源集合的长度的随机数
        Integer index = random.nextInt(list.size());
        // 获取随机数下标对应的元素
        Object obj = list.get(index);
        // 不包含该元素时
        if(!targetList.contains(obj)){
            // 添加到集合中
            targetList.add(obj);
            // 记录下标
            indexList.add(index);
        }
    }
    return indexList;}


免责声明
本站部分资源来源于互联网 如有侵权 请联系站长删除
龙哥网是优质的互联网科技创业资源_行业项目分享_网络知识引流变现方法的平台为广大网友提供学习互联网相关知识_内容变现的方法。