Java Collection Random Element random(Collection collection)

Here you can find the source of random(Collection collection)

Description

Ritorna un oggetto random della collezione.

License

Open Source License

Parameter

Parameter Description
collection a parameter

Declaration

public static Object random(Collection<?> collection) 

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.Map;
import java.util.Random;

public class Main {
    /**/*from w w  w  . j  a  v  a 2  s  . co m*/
     * Ritorna un oggetto random della collezione.
     * 
     * @param collection
     * @return
     */
    public static Object random(Collection<?> collection) {
        int index = new Random().nextInt(collection.size());
        if (collection instanceof List<?>)
            return ((List<?>) collection).get(index);

        Iterator<?> it = collection.iterator();
        Object result = null;
        for (int i = 0; it.hasNext() && i <= index; i++) // esce con i==index
            result = it.next();
        return result;
    }

    public static int size(Collection<?> collection) {
        return isEmpty(collection) ? 0 : collection.size();
    }

    /**
     * Test se la collection IS EMPTY
     * 
     * @param collection
     * @return
     */
    public static boolean isEmpty(Collection<?> collection) {
        return collection == null || collection.isEmpty();
    }

    public static boolean isEmpty(Object[] array) {
        return array == null || array.length == 0;
    }

    public static boolean isEmpty(Map<?, ?> map) {
        return map == null || map.isEmpty();
    }
}

Related

  1. nextItem(Collection items, Random random)
  2. oneOf(Collection array)
  3. peekRandom(Collection collection, Random rnd)
  4. pickOneRandomly(Collection from)
  5. pollRandom(Collection collection, Random rnd)
  6. random(Collection coll)
  7. random(Collection coll)
  8. randomElement(Collection coll)
  9. randomElement(Collection in)