假设我有一个单词列表,我想创建一个方法,将新列表的大小作为参数并返回新列表.如何从原始sourceList中获取随机单词?
public List<String> createList(int listSize) {
Random rand = new Random();
List<String> wordList = sourceWords.
stream().
limit(listSize).
collect(Collectors.toList());
return wordList;
}
Run Code Online (Sandbox Code Playgroud)
那么我如何以及在哪里使用我的随机数?
我正在尝试使用Java 8中的Streams API从集合中检索n个唯一的随机元素以进行进一步处理,但是没有太多或任何运气.
更准确地说,我想要这样的东西:
Set<Integer> subList = new HashSet<>();
Queue<Integer> collection = new PriorityQueue<>();
collection.addAll(Arrays.asList(1,2,3,4,5,6,7,8,9));
Random random = new Random();
int n = 4;
while (subList.size() < n) {
subList.add(collection.get(random.nextInt()));
}
sublist.forEach(v -> v.doSomethingFancy());
Run Code Online (Sandbox Code Playgroud)
我想尽可能高效地做到这一点.
可以这样做吗?
编辑:我的第二次尝试 - 虽然不是我的目标:
List<Integer> sublist = new ArrayList<>(collection);
Collections.shuffle(sublist);
sublist.stream().limit(n).forEach(v -> v.doSomethingFancy());
Run Code Online (Sandbox Code Playgroud)
编辑:第三次尝试(灵感来自Holger),如果coll.size()很大且n很小,这将消除大量的shuffle开销:
int n = // unique element count
List<Integer> sublist = new ArrayList<>(collection);
Random r = new Random();
for(int i = 0; i < n; i++)
Collections.swap(sublist, i, i + …Run Code Online (Sandbox Code Playgroud)