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