Java Random random(E[] elements)

Here you can find the source of random(E[] elements)

Description

random

License

Open Source License

Declaration

public static <E> E random(E[] elements) 

Method Source Code


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

import java.util.*;

public class Main {
    public static <E> E random(E[] elements) {

        return first(randomList(elements));
    }/*  w  w  w.j av  a  2  s  . com*/

    public static <E> E random(Collection<E> collection) {

        return first(randomList(collection));
    }

    public static <E> E random(E[] values, E except) {

        return random(Arrays.asList(values), except);
    }

    public static <E> E random(Collection<E> collection, E except) {

        Collection<E> randomCollection = randomList(collection);

        Iterator<E> iterator = randomCollection.iterator();

        if (iterator.hasNext()) {

            E entry = iterator.next();

            if (!Objects.equals(entry, except)) {
                return entry;
            }
        }

        return null;
    }

    public static <E> E first(Collection<E> collection) {

        if (isEmpty(collection)) {
            return null;
        }

        Iterator<E> iterator = collection.iterator();

        if (iterator.hasNext()) {
            return iterator.next();
        }

        throw new IllegalStateException("Should not happen");
    }

    public static <E> List<E> randomList(Collection<E> collection) {

        List<E> list = new ArrayList<>(collection);
        Collections.shuffle(list);

        return list;
    }

    public static <E> List<E> randomList(E[] elements) {

        return randomList(Arrays.asList(elements));
    }

    public static <E> List<E> asList(E[] array) {
        if (isEmpty(array)) {
            return new ArrayList<>();
        }

        return Arrays.asList(array);
    }

    private static <E> boolean isEmpty(Collection<E> collection) {

        return (collection == null || collection.isEmpty());
    }

    private static <E> boolean isEmpty(E[] array) {

        return (array == null || array.length == 0);
    }
}

Related

  1. randFloat(float min, float max)
  2. random()
  3. random()
  4. random()
  5. random()
  6. random(final char[] chars)
  7. random(float min, float max)
  8. random(float theStart, float theEnd)
  9. random(int min, int max)