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!?
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.
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();
}
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