Java Collection Random Element uniformSample(Collection set)

Here you can find the source of uniformSample(Collection set)

Description

Uniformly sample from a collection.

License

Open Source License

Declaration

public static Object uniformSample(Collection set) 

Method Source Code

//package com.java2s;

import java.util.Collection;
import java.util.Iterator;

import java.util.Random;

public class Main {
    private static Random rand;

    /**// w w  w .  j  a  v  a2s  .c o  m
     * Uniformly sample from a collection.
     */
    public static Object uniformSample(Collection set) {
        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();
    }

    /**
     * Returns a pseudorandom integer sampled uniformly from {0, ..., n-1} Assumes
     * n > 0
     */
    public static int randInt(int n) {
        return rand.nextInt(n);
    }
}

Related

  1. rndSubset(final Collection c, final double ratio)
  2. sampleWithReplacement(Collection c, int n)
  3. selectRandom(Collection set)
  4. selectRandom(Collection col)
  5. selectRandomSubset(Collection col, int count)