Java tutorial
//package com.java2s; import java.util.ArrayList; import java.util.Collections; import java.util.Random; public class Main { public static <T> ArrayList<T> rand(ArrayList<T> population, int nSamplesNeeded) { Random r = new Random(); ArrayList<T> ret = new ArrayList<T>(); if (nSamplesNeeded > population.size() / 2) { ArrayList<T> original = new ArrayList<T>(); original = population; while (nSamplesNeeded > 0) { int rand = r.nextInt(original.size()); if (rand < nSamplesNeeded) { ret.add(original.get(rand)); original.remove(rand); nSamplesNeeded--; } } original.clear(); } else ret = shuffle(population, nSamplesNeeded); return ret; } public static <T> ArrayList<T> shuffle(ArrayList<T> population, int sample) { ArrayList<T> newList = new ArrayList<T>(); ArrayList<T> ret = new ArrayList<T>(); newList.addAll(population); Collections.shuffle(newList); ret.addAll(newList); for (int i = sample; i < ret.size(); i++) { ret.remove(i); i--; } newList.clear(); return ret; } }