List of utility methods to do Collection Random Element
String | pickOneRandomly(Collection bad performance don't use for large sets use collections.shuffle and remove last if (from.isEmpty()) { return null; Random r = new Random(); String[] array = from.toArray(new String[] {}); int index = Math.round((float) (array.length * r.nextFloat())); try { return array[index]; ... |
K | pollRandom(Collection Returns a random element from a collection. int size = collection.size(); if (size == 0) { return null; int index = rnd.nextInt(size); List<K> values = new ArrayList<K>(collection); K retVal = values.get(index); collection.remove(retVal); ... |
Object | random(Collection> collection) Ritorna un oggetto random della collezione. 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++) result = it.next(); return result; ... |
T | random(Collection random int num = (new Random().nextInt(coll.size())); for (T t : coll) { if (--num < 0) { return t; return null; |
T | random(Collection random if (coll.size() == 0) return null; int num = (int) (Math.random() * coll.size()); for (T t : coll) if (--num < 0) return t; throw new AssertionError(); |
T | randomElement(Collection random Element int num = (int) (Math.random() * coll.size()); for (T t : coll) if (--num < 0) return t; throw new AssertionError(); |
T | randomElement(Collection { method int size = in.size(); if (size == 0) return (null); int item = 0; if (size > 1) item = randomInt(size); List<T> TheList = new ArrayList<T>(in); T ret = TheList.get(item); ... |
Iterable | randomIterable(Collection Takes given collection, shuffles it and returns iterable instance. List<T> list = new ArrayList<>(col); Collections.shuffle(list); return list; |
List | rndSubset(final Collection Returns a random subset of the specified collection, so that its size is a specified ratio of the original collection size. return rndSubset(c, (int) Math.round(c.size() * ratio)); |
Collection | sampleWithReplacement(Collection Samples with replacement from a collection return sampleWithReplacement(c, n, new Random()); |