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