Java Random getRandom(Collection collection)

Here you can find the source of getRandom(Collection collection)

Description

get Random

License

Open Source License

Declaration

public static <T> T getRandom(Collection<T> collection) 

Method Source Code

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

import java.util.*;

public class Main {
    public static final Random rnd = new Random();

    public static <T> T getRandom(Collection<T> collection) {
        if (collection.isEmpty())
            return null;
        int randomIndex = rnd.nextInt(collection.size());
        int i = 0;
        for (T obj : collection) {
            if (i == randomIndex)
                return obj;
            i = i + 1;/*  w ww . j  a  v  a 2  s.com*/
        }
        return null;
    }

    public static <T> T getRandom(List<T> list) {
        if (list.isEmpty())
            return null;
        int randomIndex = rnd.nextInt(list.size());
        return list.get(randomIndex);
    }
}

Related

  1. getOreMultiplier(int fortune, Random r)
  2. getPoisson(double lambda, Random rng)
  3. getRandom()
  4. getRandom()
  5. getRandom()
  6. getRandom(int i)
  7. getRandom(int min, int max)
  8. getRandomDigits(Random r, int l, int radix)
  9. getRandomElement(T[] items)