假设我有一个单词列表,我想创建一个方法,它将新列表的大小作为参数并返回新列表。如何从原始 sourceList 中获取随机单词?
public List<String> createList(int listSize) {
Random rand = new Random();
List<String> wordList = sourceWords.
stream().
limit(listSize).
collect(Collectors.toList());
return wordList;
}
那么我可以如何以及在哪里使用我的 Random?
最佳答案
我找到了合适的解决方案。 Random 提供了一些返回流的方法。例如 ints(size) 创建一个随机整数流。
public List<String> createList(int listSize)
{
Random rand = new Random();
List<String> wordList = rand.
ints(listSize, 0, sourceWords.size()).
mapToObj(i -> sourceWords.get(i)).
collect(Collectors.toList());
return wordList;
}
关于java - 如何从流中获取随机对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31703226/