Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Random Element from Collection

Tags:

java

I have a Collection<Obj> how do I get a random Obj from it?

I've checked the docs and there doesn't seem to be a way, since iterator is the only way to access the collection. Do I have to iterate over it to get a random object!?

like image 385
Secret Avatar asked Jan 13 '14 13:01

Secret


People also ask

How do you select a random value 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.


1 Answers

Using Lambdas you can do this quite quickly and handle the case when Collection is empty.

public static <E> Optional<E> getRandom (Collection<E> e) {

    return e.stream()
            .skip((int) (e.size() * Math.random()))
            .findFirst();
}
like image 158
Witold Kaczurba Avatar answered Sep 30 '22 14:09

Witold Kaczurba