Here you can find the source of sampleRandomSublist(List
public static <T> List<T> sampleRandomSublist(List<T> list, int sampleSize)
//package com.java2s; /******************************************************************************* * Copyright (c) 2010-2012 Nikita Zhiltsov. * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Public License v3.0 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/gpl.html//from ww w. java 2s . co m * * Contributors: * Nikita Zhiltsov - initial API and implementation * Azat Khasanshin - implementation ******************************************************************************/ import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Random; public class Main { public static <T> List<T> sampleRandomSublist(List<T> list, int sampleSize) { int size = list.size(); if (sampleSize >= size) { List<T> sublist = new ArrayList<T>(list); Collections.shuffle(sublist); return sublist; } List<T> sublist = new ArrayList<T>(); Random random = new Random(); int s = 0; while (s < sampleSize) { int index = random.nextInt(size); T element = list.get(index); if (!sublist.contains(element)) { sublist.add(element); s++; } } return sublist; } }