Here you can find the source of sampleWithReplacement(Collection
Parameter | Description |
---|---|
c | The collection to be sampled from |
n | The number of samples to take |
public static <E> Collection<E> sampleWithReplacement(Collection<E> c, int n)
//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); } } }