Java List Random Item pickOneAtRandom(List list)

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

Description

pick One At Random

License

Open Source License

Declaration

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

Method Source Code

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

import java.util.List;

import java.util.Random;

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

    public static <T> T pickOneAtRandom(List<T> list) {
        return pickOneAtRandom(list, RANDOM);
    }/*from   w  w w .j a va2  s. c  om*/

    public static <T> T pickOneAtRandom(List<T> list, Random random) {
        if (list.size() == 1) {
            return list.get(0);
        } else if (list.size() == 0) {
            throw new IllegalArgumentException("List must have at least one element");
        } else {
            int index = random.nextInt(list.size());
            return list.get(index);
        }
    }
}

Related

  1. newRandomStringList(int size, String... strings)
  2. newRandomV1(int size, int price, List oldRandomList)
  3. nextElement(List list)
  4. nextRandomElement(final List list)
  5. pickNAtRandom(List vals, int n, long seed)
  6. PickRandom(final Collection list)
  7. pickRandom(LinkedList list, int n)
  8. pickRandom(List collection)
  9. pickupFromList(String[] list)