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?
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.
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.
There are 3 ways to print the elements of a Stream in Java: forEach() println() with collect() peek()
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.
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With