Java Collection Random Element nextItem(Collection items, Random random)

Here you can find the source of nextItem(Collection items, Random random)

Description

next Item

License

LGPL

Declaration

public static <T> T nextItem(Collection<T> items, Random random) 

Method Source Code


//package com.java2s;
//License from project: LGPL 

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

public class Main {
    public static <T> T nextItem(Collection<T> items, Random random) {
        int randomIndex = random.nextInt(items.size());
        int count = 0;
        for (T item : items) {
            if (count == randomIndex)
                return item;
            count++;/*w  w  w . ja v a  2  s . c o  m*/
        }
        return null;
    }

    public static <T> T nextItem(List<T> items, Random random) {
        int randomIndex = random.nextInt(items.size());
        return items.get(randomIndex);
    }
}

Related

  1. chooseWithoutCheck(Collection collection, long seed)
  2. generateMetricsDataWithAllWrongTypes(String metricPostfix, boolean generateRandomTenant, long collectionTime)
  3. generateMetricsDataWithPartialWrongTypes(String metricPostfix, boolean generateRandomTenant, long collectionTime)
  4. getRandom(Collection collection)
  5. getRandomNumber(Collection collection, int number)
  6. oneOf(Collection array)
  7. peekRandom(Collection collection, Random rnd)
  8. pickOneRandomly(Collection from)
  9. pollRandom(Collection collection, Random rnd)