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

ObjectselectRandom(Collection set)
select Random
int random = (int) (Math.random() * set.size());
Iterator<?> iterator = set.iterator();
Object randomNode = null;
for (int i = 0; i <= random && iterator.hasNext(); i++) {
    randomNode = iterator.next();
return randomNode;
TselectRandom(Collection col)
select Random
int selected = (int) (Math.random() * col.size());
return (T) col.toArray()[selected];
ListselectRandomSubset(Collection col, int count)
Returns a list containing a random selection of elements from the specified collection.
int csize = col.size();
if (csize < count) {
    String errmsg = "Cannot select " + count + " elements " + "from a collection of only " + csize
            + " elements.";
    throw new IllegalArgumentException(errmsg);
ArrayList<T> subset = new ArrayList<T>(count);
Iterator<T> iter = col.iterator();
...
ObjectuniformSample(Collection set)
Uniformly sample from a collection.
if (set.isEmpty()) {
    return null;
int index = randInt(set.size());
Iterator setIterator = set.iterator();
for (int counter = 0; counter < index; ++counter, setIterator.next())
    ;
return setIterator.next();
...