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; 021 022import com.google.common.annotations.Beta; 023import com.google.common.annotations.GwtCompatible; 024import com.google.common.annotations.GwtIncompatible; 025import com.google.common.base.Function; 026import com.google.common.base.Optional; 027import com.google.common.base.Preconditions; 028import com.google.common.base.Predicate; 029 030import java.util.Arrays; 031import java.util.Collection; 032import java.util.Collections; 033import java.util.Comparator; 034import java.util.Iterator; 035import java.util.List; 036import java.util.NoSuchElementException; 037import java.util.Queue; 038import java.util.RandomAccess; 039import java.util.Set; 040import java.util.SortedSet; 041 042import javax.annotation.Nullable; 043 044/** 045 * This class contains static utility methods that operate on or return objects 046 * of type {@code Iterable}. Except as noted, each method has a corresponding 047 * {@link Iterator}-based method in the {@link Iterators} class. 048 * 049 * <p><i>Performance notes:</i> Unless otherwise noted, all of the iterables 050 * produced in this class are <i>lazy</i>, which means that their iterators 051 * only advance the backing iteration when absolutely necessary. 052 * 053 * <p>See the Guava User Guide article on <a href= 054 * "http://code.google.com/p/guava-libraries/wiki/CollectionUtilitiesExplained#Iterables"> 055 * {@code Iterables}</a>. 056 * 057 * @author Kevin Bourrillion 058 * @author Jared Levy 059 * @since 2.0 (imported from Google Collections Library) 060 */ 061@GwtCompatible(emulated = true) 062public final class Iterables { 063 private Iterables() {} 064 065 /** Returns an unmodifiable view of {@code iterable}. */ 066 public static <T> Iterable<T> unmodifiableIterable( 067 final Iterable<T> iterable) { 068 checkNotNull(iterable); 069 if (iterable instanceof UnmodifiableIterable || 070 iterable instanceof ImmutableCollection) { 071 return iterable; 072 } 073 return new UnmodifiableIterable<T>(iterable); 074 } 075 076 /** 077 * Simply returns its argument. 078 * 079 * @deprecated no need to use this 080 * @since 10.0 081 */ 082 @Deprecated public static <E> Iterable<E> unmodifiableIterable( 083 ImmutableCollection<E> iterable) { 084 return checkNotNull(iterable); 085 } 086 087 private static final class UnmodifiableIterable<T> extends FluentIterable<T> { 088 private final Iterable<T> iterable; 089 090 private UnmodifiableIterable(Iterable<T> iterable) { 091 this.iterable = iterable; 092 } 093 094 @Override 095 public Iterator<T> iterator() { 096 return Iterators.unmodifiableIterator(iterable.iterator()); 097 } 098 099 @Override 100 public String toString() { 101 return iterable.toString(); 102 } 103 // no equals and hashCode; it would break the contract! 104 } 105 106 /** 107 * Returns the number of elements in {@code iterable}. 108 */ 109 public static int size(Iterable<?> iterable) { 110 return (iterable instanceof Collection) 111 ? ((Collection<?>) iterable).size() 112 : Iterators.size(iterable.iterator()); 113 } 114 115 /** 116 * Returns {@code true} if {@code iterable} contains any object for which {@code equals(element)} 117 * is true. 118 */ 119 public static boolean contains(Iterable<?> iterable, @Nullable Object element) 120 { 121 if (iterable instanceof Collection) { 122 Collection<?> collection = (Collection<?>) iterable; 123 return Collections2.safeContains(collection, element); 124 } 125 return Iterators.contains(iterable.iterator(), element); 126 } 127 128 /** 129 * Removes, from an iterable, every element that belongs to the provided 130 * collection. 131 * 132 * <p>This method calls {@link Collection#removeAll} if {@code iterable} is a 133 * collection, and {@link Iterators#removeAll} otherwise. 134 * 135 * @param removeFrom the iterable to (potentially) remove elements from 136 * @param elementsToRemove the elements to remove 137 * @return {@code true} if any element was removed from {@code iterable} 138 */ 139 public static boolean removeAll( 140 Iterable<?> removeFrom, Collection<?> elementsToRemove) { 141 return (removeFrom instanceof Collection) 142 ? ((Collection<?>) removeFrom).removeAll(checkNotNull(elementsToRemove)) 143 : Iterators.removeAll(removeFrom.iterator(), elementsToRemove); 144 } 145 146 /** 147 * Removes, from an iterable, every element that does not belong to the 148 * provided collection. 149 * 150 * <p>This method calls {@link Collection#retainAll} if {@code iterable} is a 151 * collection, and {@link Iterators#retainAll} otherwise. 152 * 153 * @param removeFrom the iterable to (potentially) remove elements from 154 * @param elementsToRetain the elements to retain 155 * @return {@code true} if any element was removed from {@code iterable} 156 */ 157 public static boolean retainAll( 158 Iterable<?> removeFrom, Collection<?> elementsToRetain) { 159 return (removeFrom instanceof Collection) 160 ? ((Collection<?>) removeFrom).retainAll(checkNotNull(elementsToRetain)) 161 : Iterators.retainAll(removeFrom.iterator(), elementsToRetain); 162 } 163 164 /** 165 * Removes, from an iterable, every element that satisfies the provided 166 * predicate. 167 * 168 * @param removeFrom the iterable to (potentially) remove elements from 169 * @param predicate a predicate that determines whether an element should 170 * be removed 171 * @return {@code true} if any elements were removed from the iterable 172 * 173 * @throws UnsupportedOperationException if the iterable does not support 174 * {@code remove()}. 175 * @since 2.0 176 */ 177 public static <T> boolean removeIf( 178 Iterable<T> removeFrom, Predicate<? super T> predicate) { 179 if (removeFrom instanceof RandomAccess && removeFrom instanceof List) { 180 return removeIfFromRandomAccessList( 181 (List<T>) removeFrom, checkNotNull(predicate)); 182 } 183 return Iterators.removeIf(removeFrom.iterator(), predicate); 184 } 185 186 private static <T> boolean removeIfFromRandomAccessList( 187 List<T> list, Predicate<? super T> predicate) { 188 // Note: Not all random access lists support set() so we need to deal with 189 // those that don't and attempt the slower remove() based solution. 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 } 203 } 204 to++; 205 } 206 } 207 208 // Clear the tail of any remaining items 209 list.subList(to, list.size()).clear(); 210 return from != to; 211 } 212 213 private static <T> void slowRemoveIfForRemainingElements(List<T> list, 214 Predicate<? super T> predicate, int to, int from) { 215 // Here we know that: 216 // * (to < from) and that both are valid indices. 217 // * Everything with (index < to) should be kept. 218 // * Everything with (to <= index < from) should be removed. 219 // * The element with (index == from) should be kept. 220 // * Everything with (index > from) has not been checked yet. 221 222 // Check from the end of the list backwards (minimize expected cost of 223 // moving elements when remove() is called). Stop before 'from' because 224 // we already know that should be kept. 225 for (int n = list.size() - 1; n > from; n--) { 226 if (predicate.apply(list.get(n))) { 227 list.remove(n); 228 } 229 } 230 // And now remove everything in the range [to, from) (going backwards). 231 for (int n = from - 1; n >= to; n--) { 232 list.remove(n); 233 } 234 } 235 236 /** 237 * Determines whether two iterables contain equal elements in the same order. 238 * More specifically, this method returns {@code true} if {@code iterable1} 239 * and {@code iterable2} contain the same number of elements and every element 240 * of {@code iterable1} is equal to the corresponding element of 241 * {@code iterable2}. 242 */ 243 public static boolean elementsEqual( 244 Iterable<?> iterable1, Iterable<?> iterable2) { 245 if (iterable1 instanceof Collection && iterable2 instanceof Collection) { 246 Collection<?> collection1 = (Collection<?>) iterable1; 247 Collection<?> collection2 = (Collection<?>) iterable2; 248 if (collection1.size() != collection2.size()) { 249 return false; 250 } 251 } 252 return Iterators.elementsEqual(iterable1.iterator(), iterable2.iterator()); 253 } 254 255 /** 256 * Returns a string representation of {@code iterable}, with the format 257 * {@code [e1, e2, ..., en]}. 258 */ 259 public static String toString(Iterable<?> iterable) { 260 return Iterators.toString(iterable.iterator()); 261 } 262 263 /** 264 * Returns the single element contained in {@code iterable}. 265 * 266 * @throws NoSuchElementException if the iterable is empty 267 * @throws IllegalArgumentException if the iterable contains multiple 268 * elements 269 */ 270 public static <T> T getOnlyElement(Iterable<T> iterable) { 271 return Iterators.getOnlyElement(iterable.iterator()); 272 } 273 274 /** 275 * Returns the single element contained in {@code iterable}, or {@code 276 * defaultValue} if the iterable is empty. 277 * 278 * @throws IllegalArgumentException if the iterator contains multiple 279 * elements 280 */ 281 @Nullable 282 public static <T> T getOnlyElement( 283 Iterable<? extends T> iterable, @Nullable T defaultValue) { 284 return Iterators.getOnlyElement(iterable.iterator(), defaultValue); 285 } 286 287 /** 288 * Copies an iterable's elements into an array. 289 * 290 * @param iterable the iterable to copy 291 * @param type the type of the elements 292 * @return a newly-allocated array into which all the elements of the iterable 293 * have been copied 294 */ 295 @GwtIncompatible("Array.newInstance(Class, int)") 296 public static <T> T[] toArray(Iterable<? extends T> iterable, Class<T> type) { 297 Collection<? extends T> collection = toCollection(iterable); 298 T[] array = ObjectArrays.newArray(type, collection.size()); 299 return collection.toArray(array); 300 } 301 302 /** 303 * Copies an iterable's elements into an array. 304 * 305 * @param iterable the iterable to copy 306 * @return a newly-allocated array into which all the elements of the iterable 307 * have been copied 308 */ 309 static Object[] toArray(Iterable<?> iterable) { 310 return toCollection(iterable).toArray(); 311 } 312 313 /** 314 * Converts an iterable into a collection. If the iterable is already a 315 * collection, it is returned. Otherwise, an {@link java.util.ArrayList} is 316 * created with the contents of the iterable in the same iteration order. 317 */ 318 private static <E> Collection<E> toCollection(Iterable<E> iterable) { 319 return (iterable instanceof Collection) 320 ? (Collection<E>) iterable 321 : Lists.newArrayList(iterable.iterator()); 322 } 323 324 /** 325 * Adds all elements in {@code iterable} to {@code collection}. 326 * 327 * @return {@code true} if {@code collection} was modified as a result of this 328 * operation. 329 */ 330 public static <T> boolean addAll( 331 Collection<T> addTo, Iterable<? extends T> elementsToAdd) { 332 if (elementsToAdd instanceof Collection) { 333 Collection<? extends T> c = Collections2.cast(elementsToAdd); 334 return addTo.addAll(c); 335 } 336 return Iterators.addAll(addTo, elementsToAdd.iterator()); 337 } 338 339 /** 340 * Returns the number of elements in the specified iterable that equal the 341 * specified object. This implementation avoids a full iteration when the 342 * iterable is a {@link Multiset} or {@link Set}. 343 * 344 * @see Collections#frequency 345 */ 346 public static int frequency(Iterable<?> iterable, @Nullable Object element) { 347 if ((iterable instanceof Multiset)) { 348 return ((Multiset<?>) iterable).count(element); 349 } 350 if ((iterable instanceof Set)) { 351 return ((Set<?>) iterable).contains(element) ? 1 : 0; 352 } 353 return Iterators.frequency(iterable.iterator(), element); 354 } 355 356 /** 357 * Returns an iterable whose iterators cycle indefinitely over the elements of 358 * {@code iterable}. 359 * 360 * <p>That iterator supports {@code remove()} if {@code iterable.iterator()} 361 * does. After {@code remove()} is called, subsequent cycles omit the removed 362 * element, which is no longer in {@code iterable}. The iterator's 363 * {@code hasNext()} method returns {@code true} until {@code iterable} is 364 * empty. 365 * 366 * <p><b>Warning:</b> Typical uses of the resulting iterator may produce an 367 * infinite loop. You should use an explicit {@code break} or be certain that 368 * you will eventually remove all the elements. 369 * 370 * <p>To cycle over the iterable {@code n} times, use the following: 371 * {@code Iterables.concat(Collections.nCopies(n, iterable))} 372 */ 373 public static <T> Iterable<T> cycle(final Iterable<T> iterable) { 374 checkNotNull(iterable); 375 return new FluentIterable<T>() { 376 @Override 377 public Iterator<T> iterator() { 378 return Iterators.cycle(iterable); 379 } 380 @Override public String toString() { 381 return iterable.toString() + " (cycled)"; 382 } 383 }; 384 } 385 386 /** 387 * Returns an iterable whose iterators cycle indefinitely over the provided 388 * elements. 389 * 390 * <p>After {@code remove} is invoked on a generated iterator, the removed 391 * element will no longer appear in either that iterator or any other iterator 392 * created from the same source iterable. That is, this method behaves exactly 393 * as {@code Iterables.cycle(Lists.newArrayList(elements))}. The iterator's 394 * {@code hasNext} method returns {@code true} until all of the original 395 * elements have been removed. 396 * 397 * <p><b>Warning:</b> Typical uses of the resulting iterator may produce an 398 * infinite loop. You should use an explicit {@code break} or be certain that 399 * you will eventually remove all the elements. 400 * 401 * <p>To cycle over the elements {@code n} times, use the following: 402 * {@code Iterables.concat(Collections.nCopies(n, Arrays.asList(elements)))} 403 */ 404 public static <T> Iterable<T> cycle(T... elements) { 405 return cycle(Lists.newArrayList(elements)); 406 } 407 408 /** 409 * Combines two iterables into a single iterable. The returned iterable has an 410 * iterator that traverses the elements in {@code a}, followed by the elements 411 * in {@code b}. The source iterators are not polled until necessary. 412 * 413 * <p>The returned iterable's iterator supports {@code remove()} when the 414 * corresponding input iterator supports it. 415 */ 416 @SuppressWarnings("unchecked") 417 public static <T> Iterable<T> concat( 418 Iterable<? extends T> a, Iterable<? extends T> b) { 419 checkNotNull(a); 420 checkNotNull(b); 421 return concat(Arrays.asList(a, b)); 422 } 423 424 /** 425 * Combines three iterables into a single iterable. The returned iterable has 426 * an iterator that traverses the elements in {@code a}, followed by the 427 * elements in {@code b}, followed by the elements in {@code c}. The source 428 * 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 @SuppressWarnings("unchecked") 434 public static <T> Iterable<T> concat(Iterable<? extends T> a, 435 Iterable<? extends T> b, Iterable<? extends T> c) { 436 checkNotNull(a); 437 checkNotNull(b); 438 checkNotNull(c); 439 return concat(Arrays.asList(a, b, c)); 440 } 441 442 /** 443 * Combines four iterables into a single iterable. The returned iterable has 444 * an iterator that traverses the elements in {@code a}, followed by the 445 * elements in {@code b}, followed by the elements in {@code c}, followed by 446 * the elements in {@code d}. The source iterators are not polled until 447 * necessary. 448 * 449 * <p>The returned iterable's iterator supports {@code remove()} when the 450 * corresponding input iterator supports it. 451 */ 452 @SuppressWarnings("unchecked") 453 public static <T> Iterable<T> concat(Iterable<? extends T> a, 454 Iterable<? extends T> b, Iterable<? extends T> c, 455 Iterable<? extends T> d) { 456 checkNotNull(a); 457 checkNotNull(b); 458 checkNotNull(c); 459 checkNotNull(d); 460 return concat(Arrays.asList(a, b, c, d)); 461 } 462 463 /** 464 * Combines multiple iterables into a single iterable. The returned iterable 465 * has an iterator that traverses the elements of each iterable in 466 * {@code inputs}. The input iterators are not polled until necessary. 467 * 468 * <p>The returned iterable's iterator supports {@code remove()} when the 469 * corresponding input iterator supports it. 470 * 471 * @throws NullPointerException if any of the provided iterables is null 472 */ 473 public static <T> Iterable<T> concat(Iterable<? extends T>... inputs) { 474 return concat(ImmutableList.copyOf(inputs)); 475 } 476 477 /** 478 * Combines multiple iterables into a single iterable. The returned iterable 479 * has an iterator that traverses the elements of each iterable in 480 * {@code inputs}. The input iterators are not polled until necessary. 481 * 482 * <p>The returned iterable's iterator supports {@code remove()} when the 483 * corresponding input iterator supports it. The methods of the returned 484 * iterable may throw {@code NullPointerException} if any of the input 485 * iterators is null. 486 */ 487 public static <T> Iterable<T> concat( 488 final Iterable<? extends Iterable<? extends T>> inputs) { 489 checkNotNull(inputs); 490 return new FluentIterable<T>() { 491 @Override 492 public Iterator<T> iterator() { 493 return Iterators.concat(iterators(inputs)); 494 } 495 }; 496 } 497 498 /** 499 * Returns an iterator over the iterators of the given iterables. 500 */ 501 private static <T> UnmodifiableIterator<Iterator<? extends T>> iterators( 502 Iterable<? extends Iterable<? extends T>> iterables) { 503 final Iterator<? extends Iterable<? extends T>> iterableIterator = 504 iterables.iterator(); 505 return new UnmodifiableIterator<Iterator<? extends T>>() { 506 @Override 507 public boolean hasNext() { 508 return iterableIterator.hasNext(); 509 } 510 @Override 511 public Iterator<? extends T> next() { 512 return iterableIterator.next().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 if (iterable instanceof List) { 729 return ((List<T>) iterable).get(position); 730 } 731 732 if (iterable instanceof Collection) { 733 // Can check both ends 734 Collection<T> collection = (Collection<T>) iterable; 735 Preconditions.checkElementIndex(position, collection.size()); 736 } else { 737 // Can only check the lower end 738 checkNonnegativeIndex(position); 739 } 740 return Iterators.get(iterable.iterator(), position); 741 } 742 743 private static void checkNonnegativeIndex(int position) { 744 if (position < 0) { 745 throw new IndexOutOfBoundsException( 746 "position cannot be negative: " + position); 747 } 748 } 749 750 /** 751 * Returns the element at the specified position in an iterable or a default 752 * value otherwise. 753 * 754 * @param position position of the element to return 755 * @param defaultValue the default value to return if {@code position} is 756 * greater than or equal to the size of the iterable 757 * @return the element at the specified position in {@code iterable} or 758 * {@code defaultValue} if {@code iterable} contains fewer than 759 * {@code position + 1} elements. 760 * @throws IndexOutOfBoundsException if {@code position} is negative 761 * @since 4.0 762 */ 763 @Nullable 764 public static <T> T get(Iterable<? extends T> iterable, int position, @Nullable T defaultValue) { 765 checkNotNull(iterable); 766 checkNonnegativeIndex(position); 767 768 try { 769 return get(iterable, position); 770 } catch (IndexOutOfBoundsException e) { 771 return defaultValue; 772 } 773 } 774 775 /** 776 * Returns the first element in {@code iterable} or {@code defaultValue} if 777 * the iterable is empty. The {@link Iterators} analog to this method is 778 * {@link Iterators#getNext}. 779 * 780 * <p>If no default value is desired (and the caller instead wants a 781 * {@link NoSuchElementException} to be thrown), it is recommended that 782 * {@code iterable.iterator().next()} is used instead. 783 * 784 * @param defaultValue the default value to return if the iterable is empty 785 * @return the first element of {@code iterable} or the default value 786 * @since 7.0 787 */ 788 @Nullable 789 public static <T> T getFirst(Iterable<? extends T> iterable, @Nullable T defaultValue) { 790 return Iterators.getNext(iterable.iterator(), defaultValue); 791 } 792 793 /** 794 * Returns the last element of {@code iterable}. 795 * 796 * @return the last element of {@code iterable} 797 * @throws NoSuchElementException if the iterable is empty 798 */ 799 public static <T> T getLast(Iterable<T> iterable) { 800 // TODO(kevinb): Support a concurrently modified collection? 801 if (iterable instanceof List) { 802 List<T> list = (List<T>) iterable; 803 if (list.isEmpty()) { 804 throw new NoSuchElementException(); 805 } 806 return getLastInNonemptyList(list); 807 } 808 809 /* 810 * TODO(kevinb): consider whether this "optimization" is worthwhile. Users 811 * with SortedSets tend to know they are SortedSets and probably would not 812 * call this method. 813 */ 814 if (iterable instanceof SortedSet) { 815 SortedSet<T> sortedSet = (SortedSet<T>) iterable; 816 return sortedSet.last(); 817 } 818 819 return Iterators.getLast(iterable.iterator()); 820 } 821 822 /** 823 * Returns the last element of {@code iterable} or {@code defaultValue} if 824 * the iterable is empty. 825 * 826 * @param defaultValue the value to return if {@code iterable} is empty 827 * @return the last element of {@code iterable} or the default value 828 * @since 3.0 829 */ 830 @Nullable 831 public static <T> T getLast(Iterable<? extends T> iterable, @Nullable T defaultValue) { 832 if (iterable instanceof Collection) { 833 Collection<? extends T> collection = Collections2.cast(iterable); 834 if (collection.isEmpty()) { 835 return defaultValue; 836 } 837 } 838 839 if (iterable instanceof List) { 840 List<? extends T> list = Lists.cast(iterable); 841 return getLastInNonemptyList(list); 842 } 843 844 /* 845 * TODO(kevinb): consider whether this "optimization" is worthwhile. Users 846 * with SortedSets tend to know they are SortedSets and probably would not 847 * call this method. 848 */ 849 if (iterable instanceof SortedSet) { 850 SortedSet<? extends T> sortedSet = Sets.cast(iterable); 851 return sortedSet.last(); 852 } 853 854 return Iterators.getLast(iterable.iterator(), defaultValue); 855 } 856 857 private static <T> T getLastInNonemptyList(List<T> list) { 858 return list.get(list.size() - 1); 859 } 860 861 /** 862 * Returns a view of {@code iterable} that skips its first 863 * {@code numberToSkip} elements. If {@code iterable} contains fewer than 864 * {@code numberToSkip} elements, the returned iterable skips all of its 865 * elements. 866 * 867 * <p>Modifications to the underlying {@link Iterable} before a call to 868 * {@code iterator()} are reflected in the returned iterator. That is, the 869 * iterator skips the first {@code numberToSkip} elements that exist when the 870 * {@code Iterator} is created, not when {@code skip()} is called. 871 * 872 * <p>The returned iterable's iterator supports {@code remove()} if the 873 * iterator of the underlying iterable supports it. Note that it is 874 * <i>not</i> possible to delete the last skipped element by immediately 875 * calling {@code remove()} on that iterator, as the {@code Iterator} 876 * contract states that a call to {@code remove()} before a call to 877 * {@code next()} will throw an {@link IllegalStateException}. 878 * 879 * @since 3.0 880 */ 881 public static <T> Iterable<T> skip(final Iterable<T> iterable, 882 final int numberToSkip) { 883 checkNotNull(iterable); 884 checkArgument(numberToSkip >= 0, "number to skip cannot be negative"); 885 886 if (iterable instanceof List) { 887 final List<T> list = (List<T>) iterable; 888 return new FluentIterable<T>() { 889 @Override 890 public Iterator<T> iterator() { 891 // TODO(kevinb): Support a concurrently modified collection? 892 return (numberToSkip >= list.size()) 893 ? Iterators.<T>emptyIterator() 894 : list.subList(numberToSkip, list.size()).iterator(); 895 } 896 }; 897 } 898 899 return new FluentIterable<T>() { 900 @Override 901 public Iterator<T> iterator() { 902 final Iterator<T> iterator = iterable.iterator(); 903 904 Iterators.advance(iterator, numberToSkip); 905 906 /* 907 * We can't just return the iterator because an immediate call to its 908 * remove() method would remove one of the skipped elements instead of 909 * throwing an IllegalStateException. 910 */ 911 return new Iterator<T>() { 912 boolean atStart = true; 913 914 @Override 915 public boolean hasNext() { 916 return iterator.hasNext(); 917 } 918 919 @Override 920 public T next() { 921 if (!hasNext()) { 922 throw new NoSuchElementException(); 923 } 924 925 try { 926 return iterator.next(); 927 } finally { 928 atStart = false; 929 } 930 } 931 932 @Override 933 public void remove() { 934 if (atStart) { 935 throw new IllegalStateException(); 936 } 937 iterator.remove(); 938 } 939 }; 940 } 941 }; 942 } 943 944 /** 945 * Creates an iterable with the first {@code limitSize} elements of the given 946 * iterable. If the original iterable does not contain that many elements, the 947 * returned iterator will have the same behavior as the original iterable. The 948 * returned iterable's iterator supports {@code remove()} if the original 949 * iterator does. 950 * 951 * @param iterable the iterable to limit 952 * @param limitSize the maximum number of elements in the returned iterator 953 * @throws IllegalArgumentException if {@code limitSize} is negative 954 * @since 3.0 955 */ 956 public static <T> Iterable<T> limit( 957 final Iterable<T> iterable, final int limitSize) { 958 checkNotNull(iterable); 959 checkArgument(limitSize >= 0, "limit is negative"); 960 return new FluentIterable<T>() { 961 @Override 962 public Iterator<T> iterator() { 963 return Iterators.limit(iterable.iterator(), limitSize); 964 } 965 }; 966 } 967 968 /** 969 * Returns a view of the supplied iterable that wraps each generated 970 * {@link Iterator} through {@link Iterators#consumingIterator(Iterator)}. 971 * 972 * <p>Note: If {@code iterable} is a {@link Queue}, the returned iterable will 973 * get entries from {@link Queue#remove()} since {@link Queue}'s iteration 974 * order is undefined. Calling {@link Iterator#hasNext()} on a generated 975 * iterator from the returned iterable may cause an item to be immediately 976 * dequeued for return on a subsequent call to {@link Iterator#next()}. 977 * 978 * @param iterable the iterable to wrap 979 * @return a view of the supplied iterable that wraps each generated iterator 980 * through {@link Iterators#consumingIterator(Iterator)}; for queues, 981 * an iterable that generates iterators that return and consume the 982 * queue's elements in queue order 983 * 984 * @see Iterators#consumingIterator(Iterator) 985 * @since 2.0 986 */ 987 public static <T> Iterable<T> consumingIterable(final Iterable<T> iterable) { 988 if (iterable instanceof Queue) { 989 return new FluentIterable<T>() { 990 @Override 991 public Iterator<T> iterator() { 992 return new ConsumingQueueIterator<T>((Queue<T>) iterable); 993 } 994 }; 995 } 996 997 checkNotNull(iterable); 998 999 return new FluentIterable<T>() { 1000 @Override 1001 public Iterator<T> iterator() { 1002 return Iterators.consumingIterator(iterable.iterator()); 1003 } 1004 }; 1005 } 1006 1007 private static class ConsumingQueueIterator<T> extends AbstractIterator<T> { 1008 private final Queue<T> queue; 1009 1010 private ConsumingQueueIterator(Queue<T> queue) { 1011 this.queue = queue; 1012 } 1013 1014 @Override public T computeNext() { 1015 try { 1016 return queue.remove(); 1017 } catch (NoSuchElementException e) { 1018 return endOfData(); 1019 } 1020 } 1021 } 1022 1023 // Methods only in Iterables, not in Iterators 1024 1025 /** 1026 * Determines if the given iterable contains no elements. 1027 * 1028 * <p>There is no precise {@link Iterator} equivalent to this method, since 1029 * one can only ask an iterator whether it has any elements <i>remaining</i> 1030 * (which one does using {@link Iterator#hasNext}). 1031 * 1032 * @return {@code true} if the iterable contains no elements 1033 */ 1034 public static boolean isEmpty(Iterable<?> iterable) { 1035 if (iterable instanceof Collection) { 1036 return ((Collection<?>) iterable).isEmpty(); 1037 } 1038 return !iterable.iterator().hasNext(); 1039 } 1040 1041 /** 1042 * Returns an iterable over the merged contents of all given 1043 * {@code iterables}. Equivalent entries will not be de-duplicated. 1044 * 1045 * <p>Callers must ensure that the source {@code iterables} are in 1046 * non-descending order as this method does not sort its input. 1047 * 1048 * <p>For any equivalent elements across all {@code iterables}, it is 1049 * undefined which element is returned first. 1050 * 1051 * @since 11.0 1052 */ 1053 @Beta 1054 public static <T> Iterable<T> mergeSorted( 1055 final Iterable<? extends Iterable<? extends T>> iterables, 1056 final Comparator<? super T> comparator) { 1057 checkNotNull(iterables, "iterables"); 1058 checkNotNull(comparator, "comparator"); 1059 Iterable<T> iterable = new FluentIterable<T>() { 1060 @Override 1061 public Iterator<T> iterator() { 1062 return Iterators.mergeSorted( 1063 Iterables.transform(iterables, Iterables.<T>toIterator()), 1064 comparator); 1065 } 1066 }; 1067 return new UnmodifiableIterable<T>(iterable); 1068 } 1069 1070 // TODO(user): Is this the best place for this? Move to fluent functions? 1071 // Useful as a public method? 1072 private static <T> Function<Iterable<? extends T>, Iterator<? extends T>> 1073 toIterator() { 1074 return new Function<Iterable<? extends T>, Iterator<? extends T>>() { 1075 @Override 1076 public Iterator<? extends T> apply(Iterable<? extends T> iterable) { 1077 return iterable.iterator(); 1078 } 1079 }; 1080 } 1081}