我有一个HashSet,其中有10000个元素。我想从这个HashSet中提取随机的100个元素。所以我想我可以在集合上使用shuffle,但它不起作用。
Set<String> users = new HashSet<String>();
// for randomness, but this doesn't work
Collections.shuffle(users, new Random(System.nanoTime()));
// and use for loop to get 100 elements
我现在无法使用shuffle,有没有其他更好的方法从Java的HashSet中获取100个随机元素?
Collections.shuffle
需要一个列表(List)作为参数。因此,请尝试从您的集合(Set)创建一个List
,然后对该列表进行随机排序(shuffle)。 - Robin Krahlusers.toArray()
的结果进行洗牌。 - pjs