如何从流中获取随机对象 [英] How to get random objects from a stream
本文介绍了如何从流中获取随机对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有一个单词列表,我想创建一个方法,将新列表的大小作为参数并返回新列表。如何从原始sourceList中获取随机单词?
Lets say I have a list of words and i want to create a method which takes the size of the new list as a parameter and returns the new list. How can i get random words from my original sourceList?
public List<String> createList(int listSize) {
Random rand = new Random();
List<String> wordList = sourceWords.
stream().
limit(listSize).
collect(Collectors.toList());
return wordList;
}
那么我如何以及在哪里使用我的随机数?
So how and where can I use my Random?
推荐答案
我找到了一个合适的解决方案。
Random提供了一些返回流的方法。例如,创建随机整数流的整数(大小)。
I've found a proper solution. Random provides a few methods to return a stream. For example ints(size) which creates a stream of random integers.
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;
}
这篇关于如何从流中获取随机对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文