Here you can find the source of rndSubset(final Collection
Parameter | Description |
---|---|
T | Type parameter. |
c | Collection to pick from. |
ratio | Requested ratio. |
public static <T> List<T> rndSubset(final Collection<T> c, final double ratio)
//package com.java2s; /*//from w ww. j a va2 s . c o m * Copyright (C) 2010 vektor * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Random; public class Main { private static final Random RND = new Random(); /** * Returns a random subset of the specified collection, so that its size is a * specified ratio of the original collection size. * * @param <T> Type parameter. * @param c Collection to pick from. * @param ratio Requested ratio. * @return List of randomly picked elements of the collection. */ public static <T> List<T> rndSubset(final Collection<T> c, final double ratio) { return rndSubset(c, (int) Math.round(c.size() * ratio)); } /** * Returns a random subset of the specified collection of requested size. * * @param <T> Type parameter. * @param c Collection to pick from. * @param count Requested size of the subset. * @return List of randomly picked elements of the collection. */ public static <T> List<T> rndSubset(final Collection<T> c, final int count) { if (c == null) { throw new IllegalArgumentException("Expecting non-null parameter"); } if (count < 0) { throw new IllegalArgumentException("Size of the subset cannot be negative: " + count); } if (count > c.size()) { throw new IllegalArgumentException("Subset cannot be bigger than the original set: " + count); } final List<T> ret = new ArrayList<T>(count); final List<T> tmp = new ArrayList<T>(c); for (int i = 0; i < count; i++) { final int toRemove = RND.nextInt(tmp.size()); ret.add(tmp.get(toRemove)); tmp.remove(toRemove); } return ret; } }