Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions guava-tests/test/com/google/common/collect/IterablesTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -1440,6 +1440,11 @@ public void testIterables_nullCheck() throws Exception {
.testNulls();
}

public void testGetRandom() {
ArrayList<String> strings = Lists.newArrayList("d", "a", "o");
strings.forEach(string -> assertTrue(strings.contains(Iterables.getRandom(strings))));
}

private static void verifyMergeSorted(
Iterable<Iterable<Integer>> iterables, Iterable<Integer> unsortedExpected) {
Iterable<Integer> expected = Ordering.natural().sortedCopy(unsortedExpected);
Expand Down
14 changes: 14 additions & 0 deletions guava/src/com/google/common/collect/Iterables.java
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
import com.google.common.annotations.GwtIncompatible;
import com.google.common.base.Function;
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
Expand All @@ -34,6 +35,7 @@
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Queue;
import java.util.Random;
import java.util.RandomAccess;
import java.util.Set;
import java.util.Spliterator;
Expand Down Expand Up @@ -1017,6 +1019,18 @@ public Iterator<T> iterator() {
return new UnmodifiableIterable<>(iterable);
}

/**
* Picks up random value from {@link Iterable}.
* <p>
* Consider providing {@link Iterable} with at least 1 element,
* in other way you will get {@link IllegalArgumentException}.
* </p>
*/
public static <T> T getRandom(final Iterable<T> iterable) {
Preconditions.checkNotNull(iterable);
return Iterables.get(iterable, new Random().nextInt(Iterables.size(iterable)));
}

// TODO(user): Is this the best place for this? Move to fluent functions?
// Useful as a public method?
static <T> Function<Iterable<? extends T>, Iterator<? extends T>> toIterator() {
Expand Down