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