Java List Random Item sampleRandomSublist(List list, int sampleSize)

Here you can find the source of sampleRandomSublist(List list, int sampleSize)

Description

sample Random Sublist

License

Open Source License

Declaration

public static <T> List<T> sampleRandomSublist(List<T> list, int sampleSize) 

Method Source Code

//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;
    }
}

Related

  1. pickRandom(List collection)
  2. pickupFromList(String[] list)
  3. resampleWithReplacement(final List l, final int n)
  4. sample(List l, Random r)
  5. sample(Random random, List list)
  6. sampleWithoutReplacement(List items, int sampleSize)
  7. sampleWithReplacement(final Random random, final List data, final int sampleSize)
  8. sampleWithReplacementInto(final Random random, final List data, final int sampleSize, final Collection result)
  9. softMaxIndex(Random rand, int listSize, double temperature)