Java Collection Random Element oneOf(Collection array)

Here you can find the source of oneOf(Collection array)

Description

one Of

License

Open Source License

Declaration

public static <T> T oneOf(Collection<T> array) 

Method Source Code

//package com.java2s;
/*//from ww  w .  j av a2s.  c o  m
 * Copyright (C) 2010-2011 VTT Technical Research Centre of Finland.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation;
 * version 2.1 of the License.
 *
 * This library 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
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Random;

public class Main {
    private static Random random = new Random(100);

    public static <T> T oneOf(Collection<T> array) {
        List<T> list = new ArrayList<T>(array);
        return list.get(cInt(0, array.size() - 1));
    }

    public static int cInt() {
        return (int) Math.round(cDouble());
    }

    public static int cInt(int min, int max) {
        return (int) Math.round(cDouble(min, max));
    }

    public static double cDouble() {
        double min = Integer.MIN_VALUE;
        double max = Integer.MAX_VALUE;
        return cDouble(min, max);
    }

    public static double cDouble(double min, double max) {
        double diff = max - min;
        double rnd = random.nextDouble();
        rnd *= diff;
        rnd += min;
        return rnd;
    }
}

Related

  1. generateMetricsDataWithAllWrongTypes(String metricPostfix, boolean generateRandomTenant, long collectionTime)
  2. generateMetricsDataWithPartialWrongTypes(String metricPostfix, boolean generateRandomTenant, long collectionTime)
  3. getRandom(Collection collection)
  4. getRandomNumber(Collection collection, int number)
  5. nextItem(Collection items, Random random)
  6. peekRandom(Collection collection, Random rnd)
  7. pickOneRandomly(Collection from)
  8. pollRandom(Collection collection, Random rnd)
  9. random(Collection collection)