Java Utililty Methods Collection Random Element

List of utility methods to do Collection Random Element

Description

The list of methods to do Collection Random Element are organized into topic(s).

Method

StringpickOneRandomly(Collection from)
bad performance don't use for large sets use collections.shuffle and remove last
if (from.isEmpty()) {
    return null;
Random r = new Random();
String[] array = from.toArray(new String[] {});
int index = Math.round((float) (array.length * r.nextFloat()));
try {
    return array[index];
...
KpollRandom(Collection collection, Random rnd)
Returns a random element from a collection.
int size = collection.size();
if (size == 0) {
    return null;
int index = rnd.nextInt(size);
List<K> values = new ArrayList<K>(collection);
K retVal = values.get(index);
collection.remove(retVal);
...
Objectrandom(Collection collection)
Ritorna un oggetto random della collezione.
int index = new Random().nextInt(collection.size());
if (collection instanceof List<?>)
    return ((List<?>) collection).get(index);
Iterator<?> it = collection.iterator();
Object result = null;
for (int i = 0; it.hasNext() && i <= index; i++) 
    result = it.next();
return result;
...
Trandom(Collection coll)
random
int num = (new Random().nextInt(coll.size()));
for (T t : coll) {
    if (--num < 0) {
        return t;
return null;
Trandom(Collection coll)
random
if (coll.size() == 0)
    return null;
int num = (int) (Math.random() * coll.size());
for (T t : coll)
    if (--num < 0)
        return t;
throw new AssertionError();
TrandomElement(Collection coll)
random Element
int num = (int) (Math.random() * coll.size());
for (T t : coll)
    if (--num < 0)
        return t;
throw new AssertionError();
TrandomElement(Collection in)
{ method
int size = in.size();
if (size == 0)
    return (null);
int item = 0;
if (size > 1)
    item = randomInt(size);
List<T> TheList = new ArrayList<T>(in);
T ret = TheList.get(item);
...
IterablerandomIterable(Collection col)
Takes given collection, shuffles it and returns iterable instance.
List<T> list = new ArrayList<>(col);
Collections.shuffle(list);
return list;
ListrndSubset(final Collection c, final double ratio)
Returns a random subset of the specified collection, so that its size is a specified ratio of the original collection size.
return rndSubset(c, (int) Math.round(c.size() * ratio));
CollectionsampleWithReplacement(Collection c, int n)
Samples with replacement from a collection
return sampleWithReplacement(c, n, new Random());