Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get random objects from a stream

Tags:

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?

like image 695
Adrian Krebs Avatar asked Jul 29 '15 14:07

Adrian Krebs


People also ask

How do I get unique values from a stream?

distinct() returns a stream consisting of distinct elements in a stream. distinct() is the method of Stream interface. This method uses hashCode() and equals() methods to get distinct elements. In case of ordered streams, the selection of distinct elements is stable.

How do you randomly select from a List in Java?

In order to get a random item from a List instance, you need to generate a random index number and then fetch an item by this generated index number using List. get() method. The key point here is to remember that you mustn't use an index that exceeds your List's size.

How do I print a List element from a stream?

There are 3 ways to print the elements of a Stream in Java: forEach() println() with collect() peek()

How do you convert a List of objects into a stream of objects?

Converting a list to stream is very simple. As List extends the Collection interface, we can use the Collection. stream() method that returns a sequential stream of elements in the list.


1 Answers

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; } 
like image 152
Adrian Krebs Avatar answered Sep 28 '22 01:09

Adrian Krebs