Java Random Element randomElement(Collection coll)

Here you can find the source of randomElement(Collection coll)

Description

random Element

License

Open Source License

Declaration

public static <E> E randomElement(Collection<? extends E> coll) 

Method Source Code

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

import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Random;

public class Main {
    public static <E> E randomElement(Collection<? extends E> coll) {
        return randomElement(coll, new Random());
    }//from   www.  ja  v a2  s  .  com

    public static <E> E randomElement(Collection<? extends E> coll, Random rand) {
        if (coll.size() == 0) {
            return null;
        }

        int index = rand.nextInt(coll.size());
        if (coll instanceof List) {
            return ((List<? extends E>) coll).get(index);
        } else {
            Iterator<? extends E> iter = coll.iterator();
            for (int i = 0; i < index; i++) {
                iter.next();
            }
            return iter.next();
        }
    }
}

Related

  1. randomEle(List list)
  2. randomElem(Random rand, Set partitions)
  3. randomElement(E[] array)
  4. randomElement(final Set set)
  5. randomElement(int[] anArray)
  6. randomElement(List list)