登录
注册
写文章
发现
工具
java随机获取集合list的num个对象
_3t3lfz KEKfID
编辑文章
java随机获取集合list的num个对象
asfx站长
2020.07.02 21:42:58
阅读
1212
第一种 ``` /** * 获取随机数,随机取到0-(size-1)的值 * @param size * @return */ public static int getRandom(int size){ return new Random().nextInt(size); } /** * 集合随机取num个 * @param list * @param num * @param <T> * @return */ public static <T> List<T> getRandom(List<T> list, int num){ if(list == null || list.isEmpty() || num == 0 || list.size() <= num) return list; Set<Integer> set = new HashSet<>(); while (set.size() < num){ int random = getRandom(list.size()); set.add(random); } List<T> result = new ArrayList<>(); Iterator<Integer> iterator = set.iterator(); while (iterator.hasNext()){ Integer next = iterator.next(); result.add(list.get(next)); } //打乱顺序 Collections.shuffle(result); return result; } ``` 第二种 (**推荐!**) ``` /** * @Description 随机获取n条数据 * * 推荐 * @Param [list, num] * @return java.util.List<T> **/ public static <T> List<T> getRandomList(List<T> list, int num){ if(num > list.size()) throw new IllegalArgumentException("随机数不能大于数组长度"); List<T> randomList = new ArrayList<>(); //随机取出n条不重复的数据 for(int i = num; i >= 1; i--){ //在数组大小之间产生一个随机数 j int j = new Random().nextInt(list.size()); //取得list 中下标为j 的数据存储到 randomList 中 randomList.add(list.get(j)); //把已取到的数据移除,避免下次再次取到出现重复 list.remove(j); } return randomList; } ```
我的主页
退出