Skip to content

Commit 94e2948

Browse files
committed
[collect] Add method to get i-th element of Collections
This change adds a new method `Collections2.getElement(Collection, int)`, which returns the i-th element of the collection. Unlike existing methods via Java `Stream` or `Iterable`, the method in this change supports fast access for `ImmutableCollection`s backed by an internal array in `O(1)` instead of `O(n)` with the existing approach. Users can use this method to, e.g., retrieve a random element from `ImmutableSet` (e.g., to select a random node to connect to from a pool of nodes in a distributed system).
1 parent 0fad76f commit 94e2948

File tree

2 files changed

+6
-2
lines changed

2 files changed

+6
-2
lines changed

android/guava/src/com/google/common/collect/Iterables.java

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -777,7 +777,9 @@ public Iterator<T> iterator() {
777777
checkNotNull(iterable);
778778
return (iterable instanceof List)
779779
? ((List<T>) iterable).get(position)
780-
: Iterators.get(iterable.iterator(), position);
780+
: ((iterable instanceof ImmutableCollection)
781+
? ((ImmutableCollection<T>)iterable).asList().get(position)
782+
: Iterators.get(iterable.iterator(), position));
781783
}
782784

783785
/**

guava/src/com/google/common/collect/Iterables.java

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -767,7 +767,9 @@ public Spliterator<T> spliterator() {
767767
checkNotNull(iterable);
768768
return (iterable instanceof List)
769769
? ((List<T>) iterable).get(position)
770-
: Iterators.get(iterable.iterator(), position);
770+
: ((iterable instanceof ImmutableCollection)
771+
? ((ImmutableCollection<T>)iterable).asList().get(position)
772+
: Iterators.get(iterable.iterator(), position));
771773
}
772774

773775
/**

0 commit comments

Comments
 (0)