【发布时间】:2015-04-16 19:34:28
【问题描述】:
我有一个 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,然后随机播放这个列表。 -
随机播放
users.toArray()的结果。