Java Collection Random Element sampleWithReplacement(Collection c, int n)

Here you can find the source of sampleWithReplacement(Collection c, int n)

Description

Samples with replacement from a collection

License

Open Source License

Parameter

Parameter Description
c The collection to be sampled from
n The number of samples to take

Return

a new collection with the sample

Declaration

public static <E> Collection<E> sampleWithReplacement(Collection<E> c,
        int n) 

Method Source Code

//package com.java2s;

import java.util.ArrayList;

import java.util.Collection;

import java.util.List;

import java.util.Random;

public class Main {
    /**//from  www  .ja  va  2 s  . c o  m
     * Samples with replacement from a collection
     *
     * @param c
     *          The collection to be sampled from
     * @param n
     *          The number of samples to take
     * @return a new collection with the sample
     */
    public static <E> Collection<E> sampleWithReplacement(Collection<E> c,
            int n) {
        return sampleWithReplacement(c, n, new Random());
    }

    /**
     * Samples with replacement from a collection, using your own {@link Random}
     * number generator
     *
     * @param c
     *          The collection to be sampled from
     * @param n
     *          The number of samples to take
     * @param r
     *          the random number generator
     * @return a new collection with the sample
     */
    public static <E> Collection<E> sampleWithReplacement(Collection<E> c,
            int n, Random r) {
        if (n < 0)
            throw new IllegalArgumentException("n < 0: " + n);
        List<E> copy = new ArrayList<E>(c.size());
        copy.addAll(c);
        Collection<E> result = new ArrayList<E>(n);
        for (int k = 0; k < n; k++) {
            double d = r.nextDouble();
            int x = (int) (d * copy.size());
            result.add(copy.get(x));
        }
        return result;
    }

    /**
     * Add all the items from an iterable to a collection.
     *
     * @param <T>
     *          The type of items in the iterable and the collection
     * @param collection
     *          The collection to which the items should be added.
     * @param items
     *          The items to add to the collection.
     */
    public static <T> void addAll(Collection<T> collection,
            Iterable<? extends T> items) {
        for (T item : items) {
            collection.add(item);
        }
    }
}

Related

  1. random(Collection coll)
  2. randomElement(Collection coll)
  3. randomElement(Collection in)
  4. randomIterable(Collection col)
  5. rndSubset(final Collection c, final double ratio)
  6. selectRandom(Collection set)
  7. selectRandom(Collection col)
  8. selectRandomSubset(Collection col, int count)
  9. uniformSample(Collection set)