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