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