Java ThreadLocalRandom getRandomElement(List elements)

Here you can find the source of getRandomElement(List elements)

Description

get Random Element

License

Open Source License

Declaration

public static <T> T getRandomElement(List<T> elements) 

Method Source Code

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

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;

public class Main {
    public static <T> T getRandomElement(List<T> elements) {
        int size = elements.size();
        if (size > 0) {
            return elements.get(ThreadLocalRandom.current().nextInt(size));
        } else {/*from  w  w  w  .ja  va  2s .c  om*/
            return null;
        }
    }

    public static <T> T getRandomElement(Collection<T> elements) {
        List<T> list = new ArrayList<T>(elements);
        return getRandomElement(list);
    }
}

Related

  1. getRandom8()
  2. getRandomBetween(int min, int max)
  3. getRandomBoundedInt(int bound)
  4. getRandomDouble(double a, double b)
  5. getRandomElement(E[] array)
  6. getRandomFloat()
  7. getRandomId(@Nonnull Random random, int length)
  8. getRandomInt()
  9. getRandomInt(int a, int b)