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