1、获取集合中随机个数不重复的项,组成一个新的子集
/**
* 获取集合中随机个数不重复的项,组合新的集合
* @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、获取集合中随机个数不重复的项,获取这些项在原集合中的下标
/**
* 获取集合中随机个数不重复的项,返回下标数组
* @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;
}
发表评论