Java Collection Random Element getRandomNumber(Collection collection, int number)

Here you can find the source of getRandomNumber(Collection collection, int number)

Description

Returns at random a specific number of elements from a collection.

License

Open Source License

Parameter

Parameter Description
collection the collection
number the number of elements

Return

the random elements

Declaration

public static <T> Set<T> getRandomNumber(Collection<T> collection, int number) 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class Main {
    /**/*from   www.ja  va2 s  . co  m*/
     * Returns at random a specific number of elements from a collection.
     * @param collection the collection
     * @param number the number of elements
     * @return the random elements
     */
    public static <T> Set<T> getRandomNumber(Collection<T> collection, int number) {
        List<T> list = new ArrayList<T>(collection);
        Collections.shuffle(list);

        return new HashSet<T>(list.subList(0, number));
    }
}

Related

  1. chooseRandomThing(Collection possibleroutes)
  2. chooseWithoutCheck(Collection collection, long seed)
  3. generateMetricsDataWithAllWrongTypes(String metricPostfix, boolean generateRandomTenant, long collectionTime)
  4. generateMetricsDataWithPartialWrongTypes(String metricPostfix, boolean generateRandomTenant, long collectionTime)
  5. getRandom(Collection collection)
  6. nextItem(Collection items, Random random)
  7. oneOf(Collection array)
  8. peekRandom(Collection collection, Random rnd)
  9. pickOneRandomly(Collection from)