从Java中的列表中选择多个随机元素 [英] Pick multiple random elements from a list in Java
本文介绍了从Java中的列表中选择多个随机元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
所以说我有
List<String> teamList = new LinkedList<String>()
teamList.add("team1");
teamList.add("team2");
teamList.add("team3");
teamList.add("team4");
teamList.add("team5");
teamList.add("team6");
是否有一种简单的拣货方式......说明这个清单中的6个元素中的3个随机方式没有选择相同的元素两次(或更多次)?
Is there a simple way of picking... say 3 out the 6 elements in this list in a randomized way without picking the same element twice (or more times)?
推荐答案
试试这个:
public static List<String> pickNRandom(List<String> lst, int n) {
List<String> copy = new LinkedList<String>(lst);
Collections.shuffle(copy);
return copy.subList(0, n);
}
我假设输入列表中没有重复的元素,我采取预防措施改组副本,使原始列表不受干扰。它的调用方式如下:
I'm assuming that there are no repeated elements in the input list, also I take the precaution of shuffling a copy for leaving the original list undisturbed. It's called like this:
List<String> randomPicks = pickNRandom(teamList, 3);
这篇关于从Java中的列表中选择多个随机元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文