Java Random Element randomElement(List list)

Here you can find the source of randomElement(List list)

Description

Selects a random element from a list.

License

Apache License

Declaration

public static <T> T randomElement(List<T> list) 

Method Source Code


//package com.java2s;
//License from project: Apache License 

import java.util.List;
import java.util.Random;

public class Main {
    private static final ThreadLocal<Random> random = new ThreadLocal<Random>() {
        @Override//from   ww  w.  j  a  v  a  2 s.c  o  m
        protected Random initialValue() {
            return new Random();
        }
    };

    /** Selects a random element from a list. */
    public static <T> T randomElement(List<T> list) {
        if (list.isEmpty())
            throw new IllegalArgumentException("Can't select random element from an empty list.");
        return list.get(random.get().nextInt(list.size()));
    }
}

Related

  1. randomElem(Random rand, Set partitions)
  2. randomElement(Collection coll)
  3. randomElement(E[] array)
  4. randomElement(final Set set)
  5. randomElement(int[] anArray)
  6. randomElement(T... values)
  7. randomElement(T[] array)
  8. randomElementOf(final List list)
  9. randomElementOf(String[] array)