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