001/* 002 * Copyright (C) 2007 The Guava Authors 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016 017package com.google.common.collect; 018 019import static com.google.common.base.Preconditions.checkArgument; 020import static com.google.common.base.Preconditions.checkNotNull; 021import static com.google.common.base.Predicates.instanceOf; 022import static com.google.common.collect.CollectPreconditions.checkNonnegativeIndex; 023import static com.google.common.collect.CollectPreconditions.checkRemove; 024import static com.google.common.collect.Collections2.safeContains; 025import static com.google.common.collect.Iterators.advance; 026import static com.google.common.collect.Iterators.consumingIterator; 027import static com.google.common.collect.Iterators.getNext; 028import static com.google.common.collect.Iterators.unmodifiableIterator; 029import static com.google.common.collect.Lists.newArrayList; 030 031import com.google.common.annotations.GwtCompatible; 032import com.google.common.annotations.GwtIncompatible; 033import com.google.common.base.Function; 034import com.google.common.base.Optional; 035import com.google.common.base.Predicate; 036import com.google.errorprone.annotations.CanIgnoreReturnValue; 037import com.google.errorprone.annotations.InlineMe; 038import java.util.Collection; 039import java.util.Comparator; 040import java.util.Iterator; 041import java.util.List; 042import java.util.NoSuchElementException; 043import java.util.Queue; 044import java.util.RandomAccess; 045import java.util.Set; 046import java.util.SortedSet; 047import java.util.Spliterator; 048import java.util.function.Consumer; 049import java.util.stream.Stream; 050import org.jspecify.annotations.NonNull; 051import org.jspecify.annotations.Nullable; 052 053/** 054 * An assortment of mainly legacy static utility methods that operate on or return objects of type 055 * {@code Iterable}. Except as noted, each method has a corresponding {@link Iterator}-based method 056 * in the {@link Iterators} class. 057 * 058 * <p><b>Java 8+ users:</b> several common uses for this class are now more comprehensively 059 * addressed by the new {@link java.util.stream.Stream} library. Read the method documentation below 060 * for comparisons. This class is not being deprecated, but we gently encourage you to migrate to 061 * streams. 062 * 063 * <p><i>Performance notes:</i> Unless otherwise noted, all of the iterables produced in this class 064 * are <i>lazy</i>, which means that their iterators only advance the backing iteration when 065 * absolutely necessary. 066 * 067 * <p>See the Guava User Guide article on <a href= 068 * "https://github.com/google/guava/wiki/CollectionUtilitiesExplained#iterables">{@code 069 * Iterables}</a>. 070 * 071 * @author Kevin Bourrillion 072 * @author Jared Levy 073 * @since 2.0 074 */ 075@GwtCompatible 076public final class Iterables { 077 private Iterables() {} 078 079 /** Returns an unmodifiable view of {@code iterable}. */ 080 public static <T extends @Nullable Object> Iterable<T> unmodifiableIterable( 081 Iterable<? extends T> iterable) { 082 checkNotNull(iterable); 083 if (iterable instanceof UnmodifiableIterable || iterable instanceof ImmutableCollection) { 084 @SuppressWarnings("unchecked") // Since it's unmodifiable, the covariant cast is safe 085 Iterable<T> result = (Iterable<T>) iterable; 086 return result; 087 } 088 return new UnmodifiableIterable<>(iterable); 089 } 090 091 /** 092 * Simply returns its argument. 093 * 094 * @deprecated no need to use this 095 * @since 10.0 096 */ 097 @InlineMe( 098 replacement = "checkNotNull(iterable)", 099 staticImports = "com.google.common.base.Preconditions.checkNotNull") 100 @Deprecated 101 public static <E> Iterable<E> unmodifiableIterable(ImmutableCollection<E> iterable) { 102 return checkNotNull(iterable); 103 } 104 105 private static final class UnmodifiableIterable<T extends @Nullable Object> 106 extends FluentIterable<T> { 107 private final Iterable<? extends T> iterable; 108 109 private UnmodifiableIterable(Iterable<? extends T> iterable) { 110 this.iterable = iterable; 111 } 112 113 @Override 114 public Iterator<T> iterator() { 115 return unmodifiableIterator(iterable.iterator()); 116 } 117 118 @Override 119 public void forEach(Consumer<? super T> action) { 120 iterable.forEach(action); 121 } 122 123 @SuppressWarnings("unchecked") // safe upcast, assuming no one has a crazy Spliterator subclass 124 @Override 125 public Spliterator<T> spliterator() { 126 return (Spliterator<T>) iterable.spliterator(); 127 } 128 129 @Override 130 public String toString() { 131 return iterable.toString(); 132 } 133 // no equals and hashCode; it would break the contract! 134 } 135 136 /** Returns the number of elements in {@code iterable}. */ 137 public static int size(Iterable<?> iterable) { 138 return (iterable instanceof Collection) 139 ? ((Collection<?>) iterable).size() 140 : Iterators.size(iterable.iterator()); 141 } 142 143 /** 144 * Returns {@code true} if {@code iterable} contains any element {@code o} for which {@code 145 * Objects.equals(o, element)} would return {@code true}. Otherwise returns {@code false}, even in 146 * cases where {@link Collection#contains} might throw {@link NullPointerException} or {@link 147 * ClassCastException}. 148 */ 149 public static boolean contains(Iterable<?> iterable, @Nullable Object element) { 150 if (iterable instanceof Collection) { 151 Collection<?> collection = (Collection<?>) iterable; 152 return safeContains(collection, element); 153 } 154 return Iterators.contains(iterable.iterator(), element); 155 } 156 157 /** 158 * Removes, from an iterable, every element that belongs to the provided collection. 159 * 160 * <p>This method calls {@link Collection#removeAll} if {@code iterable} is a collection, and 161 * {@link Iterators#removeAll} otherwise. 162 * 163 * @param removeFrom the iterable to (potentially) remove elements from 164 * @param elementsToRemove the elements to remove 165 * @return {@code true} if any element was removed from {@code iterable} 166 */ 167 @CanIgnoreReturnValue 168 public static boolean removeAll(Iterable<?> removeFrom, Collection<?> elementsToRemove) { 169 return (removeFrom instanceof Collection) 170 ? ((Collection<?>) removeFrom).removeAll(checkNotNull(elementsToRemove)) 171 : Iterators.removeAll(removeFrom.iterator(), elementsToRemove); 172 } 173 174 /** 175 * Removes, from an iterable, every element that does not belong to the provided collection. 176 * 177 * <p>This method calls {@link Collection#retainAll} if {@code iterable} is a collection, and 178 * {@link Iterators#retainAll} otherwise. 179 * 180 * @param removeFrom the iterable to (potentially) remove elements from 181 * @param elementsToRetain the elements to retain 182 * @return {@code true} if any element was removed from {@code iterable} 183 */ 184 @CanIgnoreReturnValue 185 public static boolean retainAll(Iterable<?> removeFrom, Collection<?> elementsToRetain) { 186 return (removeFrom instanceof Collection) 187 ? ((Collection<?>) removeFrom).retainAll(checkNotNull(elementsToRetain)) 188 : Iterators.retainAll(removeFrom.iterator(), elementsToRetain); 189 } 190 191 /** 192 * Removes, from an iterable, every element that satisfies the provided predicate. 193 * 194 * <p>Removals may or may not happen immediately as each element is tested against the predicate. 195 * The behavior of this method is not specified if {@code predicate} is dependent on {@code 196 * removeFrom}. 197 * 198 * <p><b>Java 8+ users:</b> if {@code removeFrom} is a {@link Collection}, use {@code 199 * removeFrom.removeIf(predicate)} instead. 200 * 201 * @param removeFrom the iterable to (potentially) remove elements from 202 * @param predicate a predicate that determines whether an element should be removed 203 * @return {@code true} if any elements were removed from the iterable 204 * @throws UnsupportedOperationException if the iterable does not support {@code remove()}. 205 * @since 2.0 206 */ 207 @CanIgnoreReturnValue 208 public static <T extends @Nullable Object> boolean removeIf( 209 Iterable<T> removeFrom, Predicate<? super T> predicate) { 210 if (removeFrom instanceof Collection) { 211 return ((Collection<T>) removeFrom).removeIf(predicate); 212 } 213 return Iterators.removeIf(removeFrom.iterator(), predicate); 214 } 215 216 /** Removes and returns the first matching element, or returns {@code null} if there is none. */ 217 static <T extends @Nullable Object> @Nullable T removeFirstMatching( 218 Iterable<T> removeFrom, Predicate<? super T> predicate) { 219 checkNotNull(predicate); 220 Iterator<T> iterator = removeFrom.iterator(); 221 while (iterator.hasNext()) { 222 T next = iterator.next(); 223 if (predicate.apply(next)) { 224 iterator.remove(); 225 return next; 226 } 227 } 228 return null; 229 } 230 231 /** 232 * Determines whether two iterables contain equal elements in the same order. More specifically, 233 * this method returns {@code true} if {@code iterable1} and {@code iterable2} contain the same 234 * number of elements and every element of {@code iterable1} is equal to the corresponding element 235 * of {@code iterable2}. 236 */ 237 public static boolean elementsEqual(Iterable<?> iterable1, Iterable<?> iterable2) { 238 if (iterable1 instanceof Collection && iterable2 instanceof Collection) { 239 Collection<?> collection1 = (Collection<?>) iterable1; 240 Collection<?> collection2 = (Collection<?>) iterable2; 241 if (collection1.size() != collection2.size()) { 242 return false; 243 } 244 } 245 return Iterators.elementsEqual(iterable1.iterator(), iterable2.iterator()); 246 } 247 248 /** 249 * Returns a string representation of {@code iterable}, with the format {@code [e1, e2, ..., en]} 250 * (that is, identical to {@link java.util.Arrays Arrays}{@code 251 * .toString(Iterables.toArray(iterable))}). Note that for <i>most</i> implementations of {@link 252 * Collection}, {@code collection.toString()} also gives the same result, but that behavior is not 253 * generally guaranteed. 254 */ 255 public static String toString(Iterable<?> iterable) { 256 return Iterators.toString(iterable.iterator()); 257 } 258 259 /** 260 * Returns the single element contained in {@code iterable}. 261 * 262 * <p><b>Java 8+ users:</b> the {@code Stream} equivalent to this method is {@code 263 * stream.collect(MoreCollectors.onlyElement())}. 264 * 265 * @throws NoSuchElementException if the iterable is empty 266 * @throws IllegalArgumentException if the iterable contains multiple elements 267 */ 268 @ParametricNullness 269 public static <T extends @Nullable Object> T getOnlyElement(Iterable<T> iterable) { 270 return Iterators.getOnlyElement(iterable.iterator()); 271 } 272 273 /** 274 * Returns the single element contained in {@code iterable}, or {@code defaultValue} if the 275 * iterable is empty. 276 * 277 * <p><b>Java 8+ users:</b> the {@code Stream} equivalent to this method is {@code 278 * stream.collect(MoreCollectors.toOptional()).orElse(defaultValue)}. 279 * 280 * @throws IllegalArgumentException if the iterator contains multiple elements 281 */ 282 @ParametricNullness 283 public static <T extends @Nullable Object> T getOnlyElement( 284 Iterable<? extends T> iterable, @ParametricNullness T defaultValue) { 285 return Iterators.getOnlyElement(iterable.iterator(), defaultValue); 286 } 287 288 /** 289 * Copies an iterable's elements into an array. 290 * 291 * @param iterable the iterable to copy 292 * @param type the type of the elements 293 * @return a newly-allocated array into which all the elements of the iterable have been copied 294 */ 295 @GwtIncompatible // Array.newInstance(Class, int) 296 public static <T extends @Nullable Object> T[] toArray( 297 Iterable<? extends T> iterable, Class<@NonNull T> type) { 298 return toArray(iterable, ObjectArrays.newArray(type, 0)); 299 } 300 301 static <T extends @Nullable Object> T[] toArray(Iterable<? extends T> iterable, T[] array) { 302 Collection<? extends T> collection = castOrCopyToCollection(iterable); 303 return collection.toArray(array); 304 } 305 306 /** 307 * Copies an iterable's elements into an array. 308 * 309 * @param iterable the iterable to copy 310 * @return a newly-allocated array into which all the elements of the iterable have been copied 311 */ 312 static @Nullable Object[] toArray(Iterable<?> iterable) { 313 return castOrCopyToCollection(iterable).toArray(); 314 } 315 316 /** 317 * Converts an iterable into a collection. If the iterable is already a collection, it is 318 * returned. Otherwise, an {@link java.util.ArrayList} is created with the contents of the 319 * iterable in the same iteration order. 320 */ 321 private static <E extends @Nullable Object> Collection<E> castOrCopyToCollection( 322 Iterable<E> iterable) { 323 return (iterable instanceof Collection) 324 ? (Collection<E>) iterable 325 : newArrayList(iterable.iterator()); 326 } 327 328 /** 329 * Adds all elements in {@code iterable} to {@code collection}. 330 * 331 * @return {@code true} if {@code collection} was modified as a result of this operation. 332 */ 333 @CanIgnoreReturnValue 334 public static <T extends @Nullable Object> boolean addAll( 335 Collection<T> addTo, Iterable<? extends T> elementsToAdd) { 336 if (elementsToAdd instanceof Collection) { 337 Collection<? extends T> c = (Collection<? extends T>) elementsToAdd; 338 return addTo.addAll(c); 339 } 340 return Iterators.addAll(addTo, checkNotNull(elementsToAdd).iterator()); 341 } 342 343 /** 344 * Returns the number of elements in the specified iterable that equal the specified object. This 345 * implementation avoids a full iteration when the iterable is a {@link Multiset} or {@link Set}. 346 * 347 * <p><b>Java 8+ users:</b> In most cases, the {@code Stream} equivalent of this method is {@code 348 * stream.filter(element::equals).count()}. If {@code element} might be null, use {@code 349 * stream.filter(Predicate.isEqual(element)).count()} instead. 350 * 351 * @see java.util.Collections#frequency(Collection, Object) Collections.frequency(Collection, 352 * Object) 353 */ 354 public static int frequency(Iterable<?> iterable, @Nullable Object element) { 355 if ((iterable instanceof Multiset)) { 356 return ((Multiset<?>) iterable).count(element); 357 } else if ((iterable instanceof Set)) { 358 return ((Set<?>) iterable).contains(element) ? 1 : 0; 359 } 360 return Iterators.frequency(iterable.iterator(), element); 361 } 362 363 /** 364 * Returns an iterable whose iterators cycle indefinitely over the elements of {@code iterable}. 365 * 366 * <p>That iterator supports {@code remove()} if {@code iterable.iterator()} does. After {@code 367 * remove()} is called, subsequent cycles omit the removed element, which is no longer in {@code 368 * iterable}. The iterator's {@code hasNext()} method returns {@code true} until {@code iterable} 369 * is empty. 370 * 371 * <p><b>Warning:</b> Typical uses of the resulting iterator may produce an infinite loop. You 372 * should use an explicit {@code break} or be certain that you will eventually remove all the 373 * elements. 374 * 375 * <p>To cycle over the iterable {@code n} times, use the following: {@code 376 * Iterables.concat(Collections.nCopies(n, iterable))} 377 * 378 * <p><b>Java 8+ users:</b> The {@code Stream} equivalent of this method is {@code 379 * Stream.generate(() -> iterable).flatMap(Streams::stream)}. 380 */ 381 public static <T extends @Nullable Object> Iterable<T> cycle(Iterable<T> iterable) { 382 checkNotNull(iterable); 383 return new FluentIterable<T>() { 384 @Override 385 public Iterator<T> iterator() { 386 return Iterators.cycle(iterable); 387 } 388 389 @Override 390 public Spliterator<T> spliterator() { 391 return Stream.generate(() -> iterable).<T>flatMap(Streams::stream).spliterator(); 392 } 393 394 @Override 395 public String toString() { 396 return iterable.toString() + " (cycled)"; 397 } 398 }; 399 } 400 401 /** 402 * Returns an iterable whose iterators cycle indefinitely over the provided elements. 403 * 404 * <p>After {@code remove} is invoked on a generated iterator, the removed element will no longer 405 * appear in either that iterator or any other iterator created from the same source iterable. 406 * That is, this method behaves exactly as {@code Iterables.cycle(Lists.newArrayList(elements))}. 407 * The iterator's {@code hasNext} method returns {@code true} until all of the original elements 408 * have been removed. 409 * 410 * <p><b>Warning:</b> Typical uses of the resulting iterator may produce an infinite loop. You 411 * should use an explicit {@code break} or be certain that you will eventually remove all the 412 * elements. 413 * 414 * <p>To cycle over the elements {@code n} times, use the following: {@code 415 * Iterables.concat(Collections.nCopies(n, Arrays.asList(elements)))} 416 * 417 * <p><b>Java 8+ users:</b> If passing a single element {@code e}, the {@code Stream} equivalent 418 * of this method is {@code Stream.generate(() -> e)}. Otherwise, put the elements in a collection 419 * and use {@code Stream.generate(() -> collection).flatMap(Collection::stream)}. 420 */ 421 @SafeVarargs 422 public static <T extends @Nullable Object> Iterable<T> cycle(T... elements) { 423 return cycle(newArrayList(elements)); 424 } 425 426 /** 427 * Combines two iterables into a single iterable. The returned iterable has an iterator that 428 * traverses the elements in {@code a}, followed by the elements in {@code b}. The source 429 * iterators are not polled until necessary. 430 * 431 * <p>The returned iterable's iterator supports {@code remove()} when the corresponding input 432 * iterator supports it. 433 * 434 * <p><b>Java 8+ users:</b> The {@code Stream} equivalent of this method is {@code 435 * Stream.concat(a, b)}. 436 */ 437 public static <T extends @Nullable Object> Iterable<T> concat( 438 Iterable<? extends T> a, Iterable<? extends T> b) { 439 return FluentIterable.concat(a, b); 440 } 441 442 /** 443 * Combines three iterables into a single iterable. The returned iterable has an iterator that 444 * traverses the elements in {@code a}, followed by the elements in {@code b}, followed by the 445 * elements in {@code c}. The source iterators are not polled until necessary. 446 * 447 * <p>The returned iterable's iterator supports {@code remove()} when the corresponding input 448 * iterator supports it. 449 * 450 * <p><b>Java 8+ users:</b> The {@code Stream} equivalent of this method is {@code 451 * Streams.concat(a, b, c)}. 452 */ 453 public static <T extends @Nullable Object> Iterable<T> concat( 454 Iterable<? extends T> a, Iterable<? extends T> b, Iterable<? extends T> c) { 455 return FluentIterable.concat(a, b, c); 456 } 457 458 /** 459 * Combines four iterables into a single iterable. The returned iterable has an iterator that 460 * traverses the elements in {@code a}, followed by the elements in {@code b}, followed by the 461 * elements in {@code c}, followed by the elements in {@code d}. The source iterators are not 462 * polled until necessary. 463 * 464 * <p>The returned iterable's iterator supports {@code remove()} when the corresponding input 465 * iterator supports it. 466 * 467 * <p><b>Java 8+ users:</b> The {@code Stream} equivalent of this method is {@code 468 * Streams.concat(a, b, c, d)}. 469 */ 470 public static <T extends @Nullable Object> Iterable<T> concat( 471 Iterable<? extends T> a, 472 Iterable<? extends T> b, 473 Iterable<? extends T> c, 474 Iterable<? extends T> d) { 475 return FluentIterable.concat(a, b, c, d); 476 } 477 478 /** 479 * Combines multiple iterables into a single iterable. The returned iterable has an iterator that 480 * traverses the elements of each iterable in {@code inputs}. The input iterators are not polled 481 * until necessary. 482 * 483 * <p>The returned iterable's iterator supports {@code remove()} when the corresponding input 484 * iterator supports it. 485 * 486 * <p><b>Java 8+ users:</b> The {@code Stream} equivalent of this method is {@code 487 * Streams.concat(...)}. 488 * 489 * @throws NullPointerException if any of the provided iterables is null 490 */ 491 @SafeVarargs 492 public static <T extends @Nullable Object> Iterable<T> concat(Iterable<? extends T>... inputs) { 493 return FluentIterable.concat(inputs); 494 } 495 496 /** 497 * Combines multiple iterables into a single iterable. The returned iterable has an iterator that 498 * traverses the elements of each iterable in {@code inputs}. The input iterators are not polled 499 * until necessary. 500 * 501 * <p>The returned iterable's iterator supports {@code remove()} when the corresponding input 502 * iterator supports it. The methods of the returned iterable may throw {@code 503 * NullPointerException} if any of the input iterators is null. 504 * 505 * <p><b>Java 8+ users:</b> The {@code Stream} equivalent of this method is {@code 506 * streamOfStreams.flatMap(s -> s)}. 507 */ 508 public static <T extends @Nullable Object> Iterable<T> concat( 509 Iterable<? extends Iterable<? extends T>> inputs) { 510 return FluentIterable.concat(inputs); 511 } 512 513 /** 514 * Divides an iterable into unmodifiable sublists of the given size (the final iterable may be 515 * smaller). For example, partitioning an iterable containing {@code [a, b, c, d, e]} with a 516 * partition size of 3 yields {@code [[a, b, c], [d, e]]} -- an outer iterable containing two 517 * inner lists of three and two elements, all in the original order. 518 * 519 * <p>Iterators returned by the returned iterable do not support the {@link Iterator#remove()} 520 * method. The returned lists implement {@link RandomAccess}, whether or not the input list does. 521 * 522 * <p><b>Note:</b> The current implementation eagerly allocates storage for {@code size} elements. 523 * As a consequence, passing values like {@code Integer.MAX_VALUE} can lead to {@link 524 * OutOfMemoryError}. 525 * 526 * <p><b>Note:</b> if {@code iterable} is a {@link List}, use {@link Lists#partition(List, int)} 527 * instead. 528 * 529 * @param iterable the iterable to return a partitioned view of 530 * @param size the desired size of each partition (the last may be smaller) 531 * @return an iterable of unmodifiable lists containing the elements of {@code iterable} divided 532 * into partitions 533 * @throws IllegalArgumentException if {@code size} is nonpositive 534 */ 535 public static <T extends @Nullable Object> Iterable<List<T>> partition( 536 Iterable<T> iterable, int size) { 537 checkNotNull(iterable); 538 checkArgument(size > 0); 539 return new FluentIterable<List<T>>() { 540 @Override 541 public Iterator<List<T>> iterator() { 542 return Iterators.partition(iterable.iterator(), size); 543 } 544 }; 545 } 546 547 /** 548 * Divides an iterable into unmodifiable sublists of the given size, padding the final iterable 549 * with null values if necessary. For example, partitioning an iterable containing {@code [a, b, 550 * c, d, e]} with a partition size of 3 yields {@code [[a, b, c], [d, e, null]]} -- an outer 551 * iterable containing two inner lists of three elements each, all in the original order. 552 * 553 * <p>Iterators returned by the returned iterable do not support the {@link Iterator#remove()} 554 * method. 555 * 556 * @param iterable the iterable to return a partitioned view of 557 * @param size the desired size of each partition 558 * @return an iterable of unmodifiable lists containing the elements of {@code iterable} divided 559 * into partitions (the final iterable may have trailing null elements) 560 * @throws IllegalArgumentException if {@code size} is nonpositive 561 */ 562 public static <T extends @Nullable Object> Iterable<List<@Nullable T>> paddedPartition( 563 Iterable<T> iterable, int size) { 564 checkNotNull(iterable); 565 checkArgument(size > 0); 566 return new FluentIterable<List<@Nullable T>>() { 567 @Override 568 public Iterator<List<@Nullable T>> iterator() { 569 return Iterators.paddedPartition(iterable.iterator(), size); 570 } 571 }; 572 } 573 574 /** 575 * Returns a view of {@code unfiltered} containing all elements that satisfy the input predicate 576 * {@code retainIfTrue}. The returned iterable's iterator does not support {@code remove()}. 577 * 578 * <p><b>{@code Stream} equivalent:</b> {@link Stream#filter}. 579 */ 580 public static <T extends @Nullable Object> Iterable<T> filter( 581 Iterable<T> unfiltered, Predicate<? super T> retainIfTrue) { 582 checkNotNull(unfiltered); 583 checkNotNull(retainIfTrue); 584 return new FluentIterable<T>() { 585 @Override 586 public Iterator<T> iterator() { 587 return Iterators.filter(unfiltered.iterator(), retainIfTrue); 588 } 589 590 @Override 591 public void forEach(Consumer<? super T> action) { 592 checkNotNull(action); 593 unfiltered.forEach( 594 (@ParametricNullness T a) -> { 595 if (retainIfTrue.test(a)) { 596 action.accept(a); 597 } 598 }); 599 } 600 601 @Override 602 @GwtIncompatible // Spliterator 603 public Spliterator<T> spliterator() { 604 return CollectSpliterators.filter(unfiltered.spliterator(), retainIfTrue); 605 } 606 }; 607 } 608 609 /** 610 * Returns a view of {@code unfiltered} containing all elements that are of the type {@code 611 * desiredType}. The returned iterable's iterator does not support {@code remove()}. 612 * 613 * <p><b>{@code Stream} equivalent:</b> {@code stream.filter(type::isInstance).map(type::cast)}. 614 * This does perform a little more work than necessary, so another option is to insert an 615 * unchecked cast at some later point: 616 * 617 * {@snippet : 618 * @SuppressWarnings("unchecked") // safe because of ::isInstance check 619 * ImmutableList<NewType> result = 620 * (ImmutableList) stream.filter(NewType.class::isInstance).collect(toImmutableList()); 621 * } 622 */ 623 @SuppressWarnings("unchecked") 624 @GwtIncompatible // Class.isInstance 625 public static <T> Iterable<T> filter(Iterable<?> unfiltered, Class<T> desiredType) { 626 checkNotNull(unfiltered); 627 checkNotNull(desiredType); 628 return (Iterable<T>) filter(unfiltered, instanceOf(desiredType)); 629 } 630 631 /** 632 * Returns {@code true} if any element in {@code iterable} satisfies the predicate. 633 * 634 * <p><b>{@code Stream} equivalent:</b> {@link Stream#anyMatch}. 635 */ 636 public static <T extends @Nullable Object> boolean any( 637 Iterable<T> iterable, Predicate<? super T> predicate) { 638 return Iterators.any(iterable.iterator(), predicate); 639 } 640 641 /** 642 * Returns {@code true} if every element in {@code iterable} satisfies the predicate. If {@code 643 * iterable} is empty, {@code true} is returned. 644 * 645 * <p><b>{@code Stream} equivalent:</b> {@link Stream#allMatch}. 646 */ 647 public static <T extends @Nullable Object> boolean all( 648 Iterable<T> iterable, Predicate<? super T> predicate) { 649 return Iterators.all(iterable.iterator(), predicate); 650 } 651 652 /** 653 * Returns the first element in {@code iterable} that satisfies the given predicate; use this 654 * method only when such an element is known to exist. If it is possible that <i>no</i> element 655 * will match, use {@link #tryFind} or {@link #find(Iterable, Predicate, Object)} instead. 656 * 657 * <p><b>{@code Stream} equivalent:</b> {@code stream.filter(predicate).findFirst().get()} 658 * 659 * @throws NoSuchElementException if no element in {@code iterable} matches the given predicate 660 */ 661 @ParametricNullness 662 public static <T extends @Nullable Object> T find( 663 Iterable<T> iterable, Predicate<? super T> predicate) { 664 return Iterators.find(iterable.iterator(), predicate); 665 } 666 667 /** 668 * Returns the first element in {@code iterable} that satisfies the given predicate, or {@code 669 * defaultValue} if none found. Note that this can usually be handled more naturally using {@code 670 * tryFind(iterable, predicate).or(defaultValue)}. 671 * 672 * <p><b>{@code Stream} equivalent:</b> {@code 673 * stream.filter(predicate).findFirst().orElse(defaultValue)} 674 * 675 * @since 7.0 676 */ 677 // The signature we really want here is... 678 // 679 // <T extends @Nullable Object> @JointlyNullable T find( 680 // Iterable<? extends T> iterable, 681 // Predicate<? super T> predicate, 682 // @JointlyNullable T defaultValue); 683 // 684 // ...where "@JointlyNullable" is similar to @PolyNull but slightly different: 685 // 686 // - @PolyNull means "@Nullable or @Nonnull" 687 // (That would be unsound for an input Iterable<@Nullable Foo>. So, if we wanted to use 688 // @PolyNull, we would have to restrict this method to non-null <T>. But it has users who pass 689 // iterables with null elements.) 690 // 691 // - @JointlyNullable means "@Nullable or no annotation" 692 public static <T extends @Nullable Object> @Nullable T find( 693 Iterable<? extends T> iterable, Predicate<? super T> predicate, @Nullable T defaultValue) { 694 return Iterators.<T>find(iterable.iterator(), predicate, defaultValue); 695 } 696 697 /** 698 * Returns an {@link Optional} containing the first element in {@code iterable} that satisfies the 699 * given predicate, if such an element exists. 700 * 701 * <p><b>Warning:</b> avoid using a {@code predicate} that matches {@code null}. If {@code null} 702 * is matched in {@code iterable}, a NullPointerException will be thrown. 703 * 704 * <p><b>{@code Stream} equivalent:</b> {@code stream.filter(predicate).findFirst()} 705 * 706 * @since 11.0 707 */ 708 public static <T> Optional<T> tryFind(Iterable<T> iterable, Predicate<? super T> predicate) { 709 return Iterators.tryFind(iterable.iterator(), predicate); 710 } 711 712 /** 713 * Returns the index in {@code iterable} of the first element that satisfies the provided {@code 714 * predicate}, or {@code -1} if the Iterable has no such elements. 715 * 716 * <p>More formally, returns the lowest index {@code i} such that {@code 717 * predicate.apply(Iterables.get(iterable, i))} returns {@code true}, or {@code -1} if there is no 718 * such index. 719 * 720 * @since 2.0 721 */ 722 public static <T extends @Nullable Object> int indexOf( 723 Iterable<T> iterable, Predicate<? super T> predicate) { 724 return Iterators.indexOf(iterable.iterator(), predicate); 725 } 726 727 /** 728 * Returns a view containing the result of applying {@code function} to each element of {@code 729 * fromIterable}. 730 * 731 * <p>The returned iterable's iterator supports {@code remove()} if {@code fromIterable}'s 732 * iterator does. After a successful {@code remove()} call, {@code fromIterable} no longer 733 * contains the corresponding element. 734 * 735 * <p>If the input {@code Iterable} is known to be a {@code List} or other {@code Collection}, 736 * consider {@link Lists#transform} and {@link Collections2#transform}. 737 * 738 * <p><b>{@code Stream} equivalent:</b> {@link Stream#map} 739 */ 740 public static <F extends @Nullable Object, T extends @Nullable Object> Iterable<T> transform( 741 Iterable<F> fromIterable, Function<? super F, ? extends T> function) { 742 checkNotNull(fromIterable); 743 checkNotNull(function); 744 return new FluentIterable<T>() { 745 @Override 746 public Iterator<T> iterator() { 747 return Iterators.transform(fromIterable.iterator(), function); 748 } 749 750 @Override 751 public void forEach(Consumer<? super T> action) { 752 checkNotNull(action); 753 fromIterable.forEach((F f) -> action.accept(function.apply(f))); 754 } 755 756 @Override 757 @GwtIncompatible // Spliterator 758 public Spliterator<T> spliterator() { 759 return CollectSpliterators.map(fromIterable.spliterator(), 0, function); 760 } 761 }; 762 } 763 764 /** 765 * Returns the element at the specified position in an iterable. 766 * 767 * <p><b>{@code Stream} equivalent:</b> {@code stream.skip(position).findFirst().get()} (throws 768 * {@code NoSuchElementException} if out of bounds) 769 * 770 * @param position position of the element to return 771 * @return the element at the specified position in {@code iterable} 772 * @throws IndexOutOfBoundsException if {@code position} is negative or greater than or equal to 773 * the size of {@code iterable} 774 */ 775 @ParametricNullness 776 public static <T extends @Nullable Object> T get(Iterable<T> iterable, int position) { 777 checkNotNull(iterable); 778 return (iterable instanceof List) 779 ? ((List<T>) iterable).get(position) 780 : Iterators.get(iterable.iterator(), position); 781 } 782 783 /** 784 * Returns the element at the specified position in an iterable or a default value otherwise. 785 * 786 * <p><b>{@code Stream} equivalent:</b> {@code 787 * stream.skip(position).findFirst().orElse(defaultValue)} (returns the default value if the index 788 * is out of bounds) 789 * 790 * @param position position of the element to return 791 * @param defaultValue the default value to return if {@code position} is greater than or equal to 792 * the size of the iterable 793 * @return the element at the specified position in {@code iterable} or {@code defaultValue} if 794 * {@code iterable} contains fewer than {@code position + 1} elements. 795 * @throws IndexOutOfBoundsException if {@code position} is negative 796 * @since 4.0 797 */ 798 @ParametricNullness 799 public static <T extends @Nullable Object> T get( 800 Iterable<? extends T> iterable, int position, @ParametricNullness T defaultValue) { 801 checkNotNull(iterable); 802 checkNonnegativeIndex(position, "position"); 803 if (iterable instanceof List) { 804 List<? extends T> list = (List<? extends T>) iterable; 805 return (position < list.size()) ? list.get(position) : defaultValue; 806 } else { 807 Iterator<? extends T> iterator = iterable.iterator(); 808 advance(iterator, position); 809 return getNext(iterator, defaultValue); 810 } 811 } 812 813 /** 814 * Returns the first element in {@code iterable} or {@code defaultValue} if the iterable is empty. 815 * The {@link Iterators} analog to this method is {@link Iterators#getNext}. 816 * 817 * <p>If no default value is desired (and the caller instead wants a {@link 818 * NoSuchElementException} to be thrown), it is recommended that {@code 819 * iterable.iterator().next()} is used instead. 820 * 821 * <p>To get the only element in a single-element {@code Iterable}, consider using {@link 822 * #getOnlyElement(Iterable)} or {@link #getOnlyElement(Iterable, Object)} instead. 823 * 824 * <p><b>{@code Stream} equivalent:</b> {@code stream.findFirst().orElse(defaultValue)} 825 * 826 * <p><b>Java 21+ users:</b> if {code iterable} is a {@code SequencedCollection} (e.g., any list), 827 * consider using {@code collection.getFirst()} instead. Note that if the collection is empty, 828 * {@code getFirst()} throws a {@code NoSuchElementException}, while this method returns the 829 * default value. 830 * 831 * @param defaultValue the default value to return if the iterable is empty 832 * @return the first element of {@code iterable} or the default value 833 * @since 7.0 834 */ 835 @ParametricNullness 836 public static <T extends @Nullable Object> T getFirst( 837 Iterable<? extends T> iterable, @ParametricNullness T defaultValue) { 838 return getNext(iterable.iterator(), defaultValue); 839 } 840 841 /** 842 * Returns the last element of {@code iterable}. If {@code iterable} is a {@link List} with {@link 843 * RandomAccess} support, then this operation is guaranteed to be {@code O(1)}. 844 * 845 * <p><b>{@code Stream} equivalent:</b> {@link Streams#findLast Streams.findLast(stream).get()} 846 * 847 * <p><b>Java 21+ users:</b> if {code iterable} is a {@code SequencedCollection} (e.g., any list), 848 * consider using {@code collection.getLast()} instead. 849 * 850 * @return the last element of {@code iterable} 851 * @throws NoSuchElementException if the iterable is empty 852 */ 853 @ParametricNullness 854 public static <T extends @Nullable Object> T getLast(Iterable<T> iterable) { 855 // TODO(kevinb): Support a concurrently modified collection? 856 if (iterable instanceof List) { 857 List<T> list = (List<T>) iterable; 858 if (list.isEmpty()) { 859 throw new NoSuchElementException(); 860 } 861 return getLastInNonemptyList(list); 862 } else if (iterable instanceof SortedSet) { 863 return ((SortedSet<T>) iterable).last(); 864 } 865 866 return Iterators.getLast(iterable.iterator()); 867 } 868 869 /** 870 * Returns the last element of {@code iterable} or {@code defaultValue} if the iterable is empty. 871 * If {@code iterable} is a {@link List} with {@link RandomAccess} support, then this operation is 872 * guaranteed to be {@code O(1)}. 873 * 874 * <p><b>{@code Stream} equivalent:</b> {@code Streams.findLast(stream).orElse(defaultValue)} 875 * 876 * <p><b>Java 21+ users:</b> if {code iterable} is a {@code SequencedCollection} (e.g., any list), 877 * consider using {@code collection.getLast()} instead. Note that if the collection is empty, 878 * {@code getLast()} throws a {@code NoSuchElementException}, while this method returns the 879 * default value. 880 * 881 * @param defaultValue the value to return if {@code iterable} is empty 882 * @return the last element of {@code iterable} or the default value 883 * @since 3.0 884 */ 885 @ParametricNullness 886 public static <T extends @Nullable Object> T getLast( 887 Iterable<? extends T> iterable, @ParametricNullness T defaultValue) { 888 if (iterable instanceof Collection) { 889 Collection<? extends T> c = (Collection<? extends T>) iterable; 890 if (c.isEmpty()) { 891 return defaultValue; 892 } else if (iterable instanceof List) { 893 return getLastInNonemptyList((List<? extends T>) iterable); 894 } else if (iterable instanceof SortedSet) { 895 return ((SortedSet<? extends T>) iterable).last(); 896 } 897 } 898 899 return Iterators.getLast(iterable.iterator(), defaultValue); 900 } 901 902 @ParametricNullness 903 private static <T extends @Nullable Object> T getLastInNonemptyList(List<T> list) { 904 return list.get(list.size() - 1); 905 } 906 907 /** 908 * Returns a view of {@code iterable} that skips its first {@code numberToSkip} elements. If 909 * {@code iterable} contains fewer than {@code numberToSkip} elements, the returned iterable skips 910 * all of its elements. 911 * 912 * <p>Modifications to the underlying {@link Iterable} before a call to {@code iterator()} are 913 * reflected in the returned iterator. That is, the iterator skips the first {@code numberToSkip} 914 * elements that exist when the {@code Iterator} is created, not when {@code skip()} is called. 915 * 916 * <p>The returned iterable's iterator supports {@code remove()} if the iterator of the underlying 917 * iterable supports it. Note that it is <i>not</i> possible to delete the last skipped element by 918 * immediately calling {@code remove()} on that iterator, as the {@code Iterator} contract states 919 * that a call to {@code remove()} before a call to {@code next()} will throw an {@link 920 * IllegalStateException}. 921 * 922 * <p><b>{@code Stream} equivalent:</b> {@link Stream#skip} 923 * 924 * @since 3.0 925 */ 926 public static <T extends @Nullable Object> Iterable<T> skip( 927 Iterable<T> iterable, int numberToSkip) { 928 checkNotNull(iterable); 929 checkArgument(numberToSkip >= 0, "number to skip cannot be negative"); 930 931 return new FluentIterable<T>() { 932 @Override 933 public Iterator<T> iterator() { 934 if (iterable instanceof List) { 935 List<T> list = (List<T>) iterable; 936 int toSkip = Math.min(list.size(), numberToSkip); 937 return list.subList(toSkip, list.size()).iterator(); 938 } 939 Iterator<T> iterator = iterable.iterator(); 940 941 advance(iterator, numberToSkip); 942 943 /* 944 * We can't just return the iterator because an immediate call to its 945 * remove() method would remove one of the skipped elements instead of 946 * throwing an IllegalStateException. 947 */ 948 return new Iterator<T>() { 949 boolean atStart = true; 950 951 @Override 952 public boolean hasNext() { 953 return iterator.hasNext(); 954 } 955 956 @Override 957 @ParametricNullness 958 public T next() { 959 T result = iterator.next(); 960 atStart = false; // not called if next() fails 961 return result; 962 } 963 964 @Override 965 public void remove() { 966 checkRemove(!atStart); 967 iterator.remove(); 968 } 969 }; 970 } 971 972 @Override 973 public Spliterator<T> spliterator() { 974 if (iterable instanceof List) { 975 List<T> list = (List<T>) iterable; 976 int toSkip = Math.min(list.size(), numberToSkip); 977 return list.subList(toSkip, list.size()).spliterator(); 978 } else { 979 return Streams.stream(iterable).skip(numberToSkip).spliterator(); 980 } 981 } 982 }; 983 } 984 985 /** 986 * Returns a view of {@code iterable} containing its first {@code limitSize} elements. If {@code 987 * iterable} contains fewer than {@code limitSize} elements, the returned view contains all of its 988 * elements. The returned iterable's iterator supports {@code remove()} if {@code iterable}'s 989 * iterator does. 990 * 991 * <p><b>{@code Stream} equivalent:</b> {@link Stream#limit} 992 * 993 * @param iterable the iterable to limit 994 * @param limitSize the maximum number of elements in the returned iterable 995 * @throws IllegalArgumentException if {@code limitSize} is negative 996 * @since 3.0 997 */ 998 public static <T extends @Nullable Object> Iterable<T> limit( 999 Iterable<T> iterable, int limitSize) { 1000 checkNotNull(iterable); 1001 checkArgument(limitSize >= 0, "limit is negative"); 1002 return new FluentIterable<T>() { 1003 @Override 1004 public Iterator<T> iterator() { 1005 return Iterators.limit(iterable.iterator(), limitSize); 1006 } 1007 1008 @Override 1009 public Spliterator<T> spliterator() { 1010 return Streams.stream(iterable).limit(limitSize).spliterator(); 1011 } 1012 }; 1013 } 1014 1015 /** 1016 * Returns a view of the supplied iterable that wraps each generated {@link Iterator} through 1017 * {@link Iterators#consumingIterator(Iterator)}. 1018 * 1019 * <p>Note: If {@code iterable} is a {@link Queue}, the returned iterable will instead use {@link 1020 * Queue#isEmpty} and {@link Queue#remove()}, since {@link Queue}'s iteration order is undefined. 1021 * Calling {@link Iterator#hasNext()} on a generated iterator from the returned iterable may cause 1022 * an item to be immediately dequeued for return on a subsequent call to {@link Iterator#next()}. 1023 * 1024 * <p>Whether the input {@code iterable} is a {@link Queue} or not, the returned {@code Iterable} 1025 * is not thread-safe. 1026 * 1027 * @param iterable the iterable to wrap 1028 * @return a view of the supplied iterable that wraps each generated iterator through {@link 1029 * Iterators#consumingIterator(Iterator)}; for queues, an iterable that generates iterators 1030 * that return and consume the queue's elements in queue order 1031 * @see Iterators#consumingIterator(Iterator) 1032 * @since 2.0 1033 */ 1034 public static <T extends @Nullable Object> Iterable<T> consumingIterable(Iterable<T> iterable) { 1035 checkNotNull(iterable); 1036 1037 return new FluentIterable<T>() { 1038 @Override 1039 public Iterator<T> iterator() { 1040 return (iterable instanceof Queue) 1041 ? new ConsumingQueueIterator<>((Queue<T>) iterable) 1042 : consumingIterator(iterable.iterator()); 1043 } 1044 1045 @Override 1046 public String toString() { 1047 return "Iterables.consumingIterable(...)"; 1048 } 1049 }; 1050 } 1051 1052 // Methods only in Iterables, not in Iterators 1053 1054 /** 1055 * Determines if the given iterable contains no elements. 1056 * 1057 * <p>There is no precise {@link Iterator} equivalent to this method, since one can only ask an 1058 * iterator whether it has any elements <i>remaining</i> (which one does using {@link 1059 * Iterator#hasNext}). 1060 * 1061 * <p><b>{@code Stream} equivalent:</b> {@code !stream.findAny().isPresent()} 1062 * 1063 * @return {@code true} if the iterable contains no elements 1064 */ 1065 public static boolean isEmpty(Iterable<?> iterable) { 1066 if (iterable instanceof Collection) { 1067 return ((Collection<?>) iterable).isEmpty(); 1068 } 1069 return !iterable.iterator().hasNext(); 1070 } 1071 1072 /** 1073 * Returns an iterable over the merged contents of all given {@code iterables}. Equivalent entries 1074 * will not be de-duplicated. 1075 * 1076 * <p>Callers must ensure that the source {@code iterables} are in non-descending order as this 1077 * method does not sort its input. 1078 * 1079 * <p>For any equivalent elements across all {@code iterables}, elements are returned in the order 1080 * of their source iterables. That is, if element A from iterable 1 and element B from iterable 2 1081 * compare as equal, A will be returned before B if iterable 1 was passed before iterable 2. 1082 * 1083 * @since 11.0 1084 */ 1085 public static <T extends @Nullable Object> Iterable<T> mergeSorted( 1086 Iterable<? extends Iterable<? extends T>> iterables, Comparator<? super T> comparator) { 1087 checkNotNull(iterables, "iterables"); 1088 checkNotNull(comparator, "comparator"); 1089 Iterable<T> iterable = 1090 new FluentIterable<T>() { 1091 @Override 1092 public Iterator<T> iterator() { 1093 return Iterators.mergeSorted( 1094 Iterables.transform(iterables, Iterable::iterator), comparator); 1095 } 1096 }; 1097 return new UnmodifiableIterable<>(iterable); 1098 } 1099}