From 94e2948ba519aedad5dd24b20306a0343c5fcf67 Mon Sep 17 00:00:00 2001 From: Yannic Bonenberger Date: Tue, 22 Jul 2025 12:37:49 +0200 Subject: [PATCH] [collect] Add method to get `i-th` element of `Collection`s 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). --- android/guava/src/com/google/common/collect/Iterables.java | 4 +++- guava/src/com/google/common/collect/Iterables.java | 4 +++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/android/guava/src/com/google/common/collect/Iterables.java b/android/guava/src/com/google/common/collect/Iterables.java index 585ce6bed0be..afb6dfc43450 100644 --- a/android/guava/src/com/google/common/collect/Iterables.java +++ b/android/guava/src/com/google/common/collect/Iterables.java @@ -777,7 +777,9 @@ public Iterator iterator() { checkNotNull(iterable); return (iterable instanceof List) ? ((List) iterable).get(position) - : Iterators.get(iterable.iterator(), position); + : ((iterable instanceof ImmutableCollection) + ? ((ImmutableCollection)iterable).asList().get(position) + : Iterators.get(iterable.iterator(), position)); } /** diff --git a/guava/src/com/google/common/collect/Iterables.java b/guava/src/com/google/common/collect/Iterables.java index 79b908d45959..b4b5e583af48 100644 --- a/guava/src/com/google/common/collect/Iterables.java +++ b/guava/src/com/google/common/collect/Iterables.java @@ -767,7 +767,9 @@ public Spliterator spliterator() { checkNotNull(iterable); return (iterable instanceof List) ? ((List) iterable).get(position) - : Iterators.get(iterable.iterator(), position); + : ((iterable instanceof ImmutableCollection) + ? ((ImmutableCollection)iterable).asList().get(position) + : Iterators.get(iterable.iterator(), position)); } /**