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