JAVA获取集合中随机N个元素
public static List<Long> getRandomList(List<Long> ids, int count) {
List<Long> res = new ArrayList<>();
for (int i = 0; i < count; i++) {
int random = getRandom(ids.size() - 1);
res.add(ids.get(random));
ids.remove(random);
}
return res;
}
public static List<Integer> getRandomList(int size, int count) {
List<Integer> allList = new ArrayList<>();
List<Integer> res = new ArrayList<>();
for (int i = 0; i < size; i++) {
allList.add(i);
}
for (int i = 0; i < count; i++) {
int random = getRandom(allList.size() - 1);
res.add(allList.get(random));
allList.remove(random);
}
return res;
}
public static int getRandom(int start, int end) {
BigDecimal max = BigDecimal.valueOf(end + 2);
BigDecimal min = BigDecimal.valueOf(start);
int random;
do {
random = max.subtract(min).multiply(BigDecimal.valueOf(Math.random())).add(min).setScale(0, RoundingMode.HALF_UP).intValue();
} while (random == start || random == end + 2);
return random - 1;
}