Java ThreadLocalRandom randomElement(Collection c, int n, boolean unique)

Here you can find the source of randomElement(Collection c, int n, boolean unique)

Description

Selects pseudo-random elements from a collection

License

Open Source License

Parameter

Parameter Description
c Collection to select from
n Number of elements to select
unique Whether the selection should be unique

Return

Random element(s) from collection

Declaration

public static <E> Collection<E> randomElement(Collection<E> c, int n, boolean unique) 

Method Source Code


//package com.java2s;
/*//from  w  w w.  j  av a  2  s  .c  o  m
 * Copyright (c) 2016.
 * This file is part of OFlib.
 *
 * OFlib 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.
 *
 * OFlib 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 OFlib.  If not, see <http://www.gnu.org/licenses/>.
 */

import java.util.*;
import java.util.concurrent.ThreadLocalRandom;

public class Main {
    /**
     * Selects pseudo-random elements from a collection
     *
     * @param c      Collection to select from
     * @param n      Number of elements to select
     * @param unique Whether the selection should be unique
     * @return Random element(s) from collection
     */
    public static <E> Collection<E> randomElement(Collection<E> c, int n, boolean unique) {
        List<E> out = new ArrayList<>();
        List<E> l = new ArrayList<>(c);

        while (out.size() < n) {
            E e = l.get(ThreadLocalRandom.current().nextInt(0, l.size()));
            out.add(e);
            if (unique)
                l.remove(e);
        }
        return out;
    }
}

Related

  1. randomBoundedInclusiveInt(int start, int end)
  2. randomCase(String input)
  3. randomChar()
  4. randomDelay()
  5. randomDouble(final double min, final double max)
  6. randomEnum(Class clazz)
  7. randomFishType()
  8. randomFixedChars(int size, List pool)
  9. randomIndexs(int count, int bound)