Search code examples
javajava-8java-stream

How to get random objects from a stream


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?


Solution

  • 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;
    }