Java List Random Item nextElement(List list)

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

Description

Gets a random element from the given list.

License

Open Source License

Parameter

Parameter Description
T The type of the elements of the given list.
list The given list to select an element from.

Return

A random element from the given list.

Declaration

public static <T> T nextElement(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 RandomInstance = new Random();

    /**//from  w  w  w. ja v a  2 s  .c  om
     * Gets a random element from the given list.
     *
     * @param <T> The type of the elements of the given list.
     * @param list The given list to select an element from.
     * @return A random element from the given list.
     * @note If the list is not effective or has a size of zero, <c>null</c> is
     * returned.
     * @note If the list contains non-effective elements, <c>null</c> may be
     * returned.
     */
    public static <T> T nextElement(List<T> list) {
        if (list != null) {
            int n = list.size();
            if (n > 0x00) {
                return list.get(nextInt(n));
            }
        }
        return null;
    }

    /**
     * Gets a random element from the given list.
     *
     * @param <T> The type of the elements of the given array.
     * @param array The given array to select an element from.
     * @return A random element from the given array.
     * @note If the array is not effective or has a size of zero, <c>null</c> is
     * returned.
     * @note If the array contains non-effective elements, <c>null</c> may be
     * returned.
     */
    public static <T> T nextElement(T[] array) {
        if (array != null) {
            int n = array.length;
            if (n > 0x00) {
                return array[nextInt(n)];
            }
        }
        return null;
    }

    public static int nextInt() {
        return RandomInstance.nextInt();
    }

    public static int nextInt(int n) {
        return RandomInstance.nextInt(n);
    }
}

Related

  1. makeRandomList(int arraySize, boolean unique)
  2. newRandom(int size, int price, List oldRandomList)
  3. newRandomIntegerList(int size)
  4. newRandomStringList(int size, String... strings)
  5. newRandomV1(int size, int price, List oldRandomList)
  6. nextRandomElement(final List list)
  7. pickNAtRandom(List vals, int n, long seed)
  8. pickOneAtRandom(List list)
  9. PickRandom(final Collection list)