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.base.Preconditions.checkState; 022import static com.google.common.base.Predicates.instanceOf; 023import static com.google.common.collect.CollectPreconditions.checkRemove; 024 025import com.google.common.annotations.Beta; 026import com.google.common.annotations.GwtCompatible; 027import com.google.common.annotations.GwtIncompatible; 028import com.google.common.base.Function; 029import com.google.common.base.Objects; 030import com.google.common.base.Optional; 031import com.google.common.base.Preconditions; 032import com.google.common.base.Predicate; 033import com.google.common.primitives.Ints; 034import com.google.errorprone.annotations.CanIgnoreReturnValue; 035import java.util.ArrayDeque; 036import java.util.Arrays; 037import java.util.Collection; 038import java.util.Collections; 039import java.util.Comparator; 040import java.util.Deque; 041import java.util.Enumeration; 042import java.util.Iterator; 043import java.util.List; 044import java.util.ListIterator; 045import java.util.NoSuchElementException; 046import java.util.PriorityQueue; 047import java.util.Queue; 048import org.checkerframework.checker.nullness.qual.Nullable; 049 050/** 051 * This class contains static utility methods that operate on or return objects of type {@link 052 * Iterator}. Except as noted, each method has a corresponding {@link Iterable}-based method in the 053 * {@link Iterables} class. 054 * 055 * <p><i>Performance notes:</i> Unless otherwise noted, all of the iterators produced in this class 056 * are <i>lazy</i>, which means that they only advance the backing iteration when absolutely 057 * necessary. 058 * 059 * <p>See the Guava User Guide section on <a href= 060 * "https://github.com/google/guava/wiki/CollectionUtilitiesExplained#iterables"> {@code 061 * Iterators}</a>. 062 * 063 * @author Kevin Bourrillion 064 * @author Jared Levy 065 * @since 2.0 066 */ 067@GwtCompatible(emulated = true) 068public final class Iterators { 069 private Iterators() {} 070 071 /** 072 * Returns the empty iterator. 073 * 074 * <p>The {@link Iterable} equivalent of this method is {@link ImmutableSet#of()}. 075 */ 076 static <T> UnmodifiableIterator<T> emptyIterator() { 077 return emptyListIterator(); 078 } 079 080 /** 081 * Returns the empty iterator. 082 * 083 * <p>The {@link Iterable} equivalent of this method is {@link ImmutableSet#of()}. 084 */ 085 // Casting to any type is safe since there are no actual elements. 086 @SuppressWarnings("unchecked") 087 static <T> UnmodifiableListIterator<T> emptyListIterator() { 088 return (UnmodifiableListIterator<T>) ArrayItr.EMPTY; 089 } 090 091 /** 092 * This is an enum singleton rather than an anonymous class so ProGuard can figure out it's only 093 * referenced by emptyModifiableIterator(). 094 */ 095 private enum EmptyModifiableIterator implements Iterator<Object> { 096 INSTANCE; 097 098 @Override 099 public boolean hasNext() { 100 return false; 101 } 102 103 @Override 104 public Object next() { 105 throw new NoSuchElementException(); 106 } 107 108 @Override 109 public void remove() { 110 checkRemove(false); 111 } 112 } 113 114 /** 115 * Returns the empty {@code Iterator} that throws {@link IllegalStateException} instead of {@link 116 * UnsupportedOperationException} on a call to {@link Iterator#remove()}. 117 */ 118 // Casting to any type is safe since there are no actual elements. 119 @SuppressWarnings("unchecked") 120 static <T> Iterator<T> emptyModifiableIterator() { 121 return (Iterator<T>) EmptyModifiableIterator.INSTANCE; 122 } 123 124 /** Returns an unmodifiable view of {@code iterator}. */ 125 public static <T> UnmodifiableIterator<T> unmodifiableIterator( 126 final Iterator<? extends T> iterator) { 127 checkNotNull(iterator); 128 if (iterator instanceof UnmodifiableIterator) { 129 @SuppressWarnings("unchecked") // Since it's unmodifiable, the covariant cast is safe 130 UnmodifiableIterator<T> result = (UnmodifiableIterator<T>) iterator; 131 return result; 132 } 133 return new UnmodifiableIterator<T>() { 134 @Override 135 public boolean hasNext() { 136 return iterator.hasNext(); 137 } 138 139 @Override 140 public T next() { 141 return iterator.next(); 142 } 143 }; 144 } 145 146 /** 147 * Simply returns its argument. 148 * 149 * @deprecated no need to use this 150 * @since 10.0 151 */ 152 @Deprecated 153 public static <T> UnmodifiableIterator<T> unmodifiableIterator(UnmodifiableIterator<T> iterator) { 154 return checkNotNull(iterator); 155 } 156 157 /** 158 * Returns the number of elements remaining in {@code iterator}. The iterator will be left 159 * exhausted: its {@code hasNext()} method will return {@code false}. 160 */ 161 public static int size(Iterator<?> iterator) { 162 long count = 0L; 163 while (iterator.hasNext()) { 164 iterator.next(); 165 count++; 166 } 167 return Ints.saturatedCast(count); 168 } 169 170 /** Returns {@code true} if {@code iterator} contains {@code element}. */ 171 public static boolean contains(Iterator<?> iterator, @Nullable Object element) { 172 if (element == null) { 173 while (iterator.hasNext()) { 174 if (iterator.next() == null) { 175 return true; 176 } 177 } 178 } else { 179 while (iterator.hasNext()) { 180 if (element.equals(iterator.next())) { 181 return true; 182 } 183 } 184 } 185 return false; 186 } 187 188 /** 189 * Traverses an iterator and removes every element that belongs to the provided collection. The 190 * iterator will be left exhausted: its {@code hasNext()} method will return {@code false}. 191 * 192 * @param removeFrom the iterator to (potentially) remove elements from 193 * @param elementsToRemove the elements to remove 194 * @return {@code true} if any element was removed from {@code iterator} 195 */ 196 @CanIgnoreReturnValue 197 public static boolean removeAll(Iterator<?> removeFrom, Collection<?> elementsToRemove) { 198 checkNotNull(elementsToRemove); 199 boolean result = false; 200 while (removeFrom.hasNext()) { 201 if (elementsToRemove.contains(removeFrom.next())) { 202 removeFrom.remove(); 203 result = true; 204 } 205 } 206 return result; 207 } 208 209 /** 210 * Removes every element that satisfies the provided predicate from the iterator. The iterator 211 * will be left exhausted: its {@code hasNext()} method will return {@code false}. 212 * 213 * @param removeFrom the iterator to (potentially) remove elements from 214 * @param predicate a predicate that determines whether an element should be removed 215 * @return {@code true} if any elements were removed from the iterator 216 * @since 2.0 217 */ 218 @CanIgnoreReturnValue 219 public static <T> boolean removeIf(Iterator<T> removeFrom, Predicate<? super T> predicate) { 220 checkNotNull(predicate); 221 boolean modified = false; 222 while (removeFrom.hasNext()) { 223 if (predicate.apply(removeFrom.next())) { 224 removeFrom.remove(); 225 modified = true; 226 } 227 } 228 return modified; 229 } 230 231 /** 232 * Traverses an iterator and removes every element that does not belong to the provided 233 * collection. The iterator will be left exhausted: its {@code hasNext()} method will return 234 * {@code false}. 235 * 236 * @param removeFrom the iterator to (potentially) remove elements from 237 * @param elementsToRetain the elements to retain 238 * @return {@code true} if any element was removed from {@code iterator} 239 */ 240 @CanIgnoreReturnValue 241 public static boolean retainAll(Iterator<?> removeFrom, Collection<?> elementsToRetain) { 242 checkNotNull(elementsToRetain); 243 boolean result = false; 244 while (removeFrom.hasNext()) { 245 if (!elementsToRetain.contains(removeFrom.next())) { 246 removeFrom.remove(); 247 result = true; 248 } 249 } 250 return result; 251 } 252 253 /** 254 * Determines whether two iterators contain equal elements in the same order. More specifically, 255 * this method returns {@code true} if {@code iterator1} and {@code iterator2} contain the same 256 * number of elements and every element of {@code iterator1} is equal to the corresponding element 257 * of {@code iterator2}. 258 * 259 * <p>Note that this will modify the supplied iterators, since they will have been advanced some 260 * number of elements forward. 261 */ 262 public static boolean elementsEqual(Iterator<?> iterator1, Iterator<?> iterator2) { 263 while (iterator1.hasNext()) { 264 if (!iterator2.hasNext()) { 265 return false; 266 } 267 Object o1 = iterator1.next(); 268 Object o2 = iterator2.next(); 269 if (!Objects.equal(o1, o2)) { 270 return false; 271 } 272 } 273 return !iterator2.hasNext(); 274 } 275 276 /** 277 * Returns a string representation of {@code iterator}, with the format {@code [e1, e2, ..., en]}. 278 * The iterator will be left exhausted: its {@code hasNext()} method will return {@code false}. 279 */ 280 public static String toString(Iterator<?> iterator) { 281 StringBuilder sb = new StringBuilder().append('['); 282 boolean first = true; 283 while (iterator.hasNext()) { 284 if (!first) { 285 sb.append(", "); 286 } 287 first = false; 288 sb.append(iterator.next()); 289 } 290 return sb.append(']').toString(); 291 } 292 293 /** 294 * Returns the single element contained in {@code iterator}. 295 * 296 * @throws NoSuchElementException if the iterator is empty 297 * @throws IllegalArgumentException if the iterator contains multiple elements. The state of the 298 * iterator is unspecified. 299 */ 300 @CanIgnoreReturnValue // TODO(kak): Consider removing this? 301 public static <T> T getOnlyElement(Iterator<T> iterator) { 302 T first = iterator.next(); 303 if (!iterator.hasNext()) { 304 return first; 305 } 306 307 StringBuilder sb = new StringBuilder().append("expected one element but was: <").append(first); 308 for (int i = 0; i < 4 && iterator.hasNext(); i++) { 309 sb.append(", ").append(iterator.next()); 310 } 311 if (iterator.hasNext()) { 312 sb.append(", ..."); 313 } 314 sb.append('>'); 315 316 throw new IllegalArgumentException(sb.toString()); 317 } 318 319 /** 320 * Returns the single element contained in {@code iterator}, or {@code defaultValue} if the 321 * iterator is empty. 322 * 323 * @throws IllegalArgumentException if the iterator contains multiple elements. The state of the 324 * iterator is unspecified. 325 */ 326 @CanIgnoreReturnValue // TODO(kak): Consider removing this? 327 public static <T> @Nullable T getOnlyElement( 328 Iterator<? extends T> iterator, @Nullable T defaultValue) { 329 return iterator.hasNext() ? getOnlyElement(iterator) : defaultValue; 330 } 331 332 /** 333 * Copies an iterator's elements into an array. The iterator will be left exhausted: its {@code 334 * hasNext()} method will return {@code false}. 335 * 336 * @param iterator the iterator to copy 337 * @param type the type of the elements 338 * @return a newly-allocated array into which all the elements of the iterator have been copied 339 */ 340 @GwtIncompatible // Array.newInstance(Class, int) 341 public static <T> T[] toArray(Iterator<? extends T> iterator, Class<T> type) { 342 List<T> list = Lists.newArrayList(iterator); 343 return Iterables.toArray(list, type); 344 } 345 346 /** 347 * Adds all elements in {@code iterator} to {@code collection}. The iterator will be left 348 * exhausted: its {@code hasNext()} method will return {@code false}. 349 * 350 * @return {@code true} if {@code collection} was modified as a result of this operation 351 */ 352 @CanIgnoreReturnValue 353 public static <T> boolean addAll(Collection<T> addTo, Iterator<? extends T> iterator) { 354 checkNotNull(addTo); 355 checkNotNull(iterator); 356 boolean wasModified = false; 357 while (iterator.hasNext()) { 358 wasModified |= addTo.add(iterator.next()); 359 } 360 return wasModified; 361 } 362 363 /** 364 * Returns the number of elements in the specified iterator that equal the specified object. The 365 * iterator will be left exhausted: its {@code hasNext()} method will return {@code false}. 366 * 367 * @see Collections#frequency 368 */ 369 public static int frequency(Iterator<?> iterator, @Nullable Object element) { 370 int count = 0; 371 while (contains(iterator, element)) { 372 // Since it lives in the same class, we know contains gets to the element and then stops, 373 // though that isn't currently publicly documented. 374 count++; 375 } 376 return count; 377 } 378 379 /** 380 * Returns an iterator that cycles indefinitely over the elements of {@code iterable}. 381 * 382 * <p>The returned iterator supports {@code remove()} if the provided iterator does. After {@code 383 * remove()} is called, subsequent cycles omit the removed element, which is no longer in {@code 384 * iterable}. The iterator's {@code hasNext()} method returns {@code true} until {@code iterable} 385 * is empty. 386 * 387 * <p><b>Warning:</b> Typical uses of the resulting iterator may produce an infinite loop. You 388 * should use an explicit {@code break} or be certain that you will eventually remove all the 389 * elements. 390 */ 391 public static <T> Iterator<T> cycle(final Iterable<T> iterable) { 392 checkNotNull(iterable); 393 return new Iterator<T>() { 394 Iterator<T> iterator = emptyModifiableIterator(); 395 396 @Override 397 public boolean hasNext() { 398 /* 399 * Don't store a new Iterator until we know the user can't remove() the last returned 400 * element anymore. Otherwise, when we remove from the old iterator, we may be invalidating 401 * the new one. The result is a ConcurrentModificationException or other bad behavior. 402 * 403 * (If we decide that we really, really hate allocating two Iterators per cycle instead of 404 * one, we can optimistically store the new Iterator and then be willing to throw it out if 405 * the user calls remove().) 406 */ 407 return iterator.hasNext() || iterable.iterator().hasNext(); 408 } 409 410 @Override 411 public T next() { 412 if (!iterator.hasNext()) { 413 iterator = iterable.iterator(); 414 if (!iterator.hasNext()) { 415 throw new NoSuchElementException(); 416 } 417 } 418 return iterator.next(); 419 } 420 421 @Override 422 public void remove() { 423 iterator.remove(); 424 } 425 }; 426 } 427 428 /** 429 * Returns an iterator that cycles indefinitely over the provided elements. 430 * 431 * <p>The returned iterator supports {@code remove()}. After {@code remove()} is called, 432 * subsequent cycles omit the removed element, but {@code elements} does not change. The 433 * iterator's {@code hasNext()} method returns {@code true} until all of the original elements 434 * have been removed. 435 * 436 * <p><b>Warning:</b> Typical uses of the resulting iterator may produce an infinite loop. You 437 * should use an explicit {@code break} or be certain that you will eventually remove all the 438 * elements. 439 */ 440 @SafeVarargs 441 public static <T> Iterator<T> cycle(T... elements) { 442 return cycle(Lists.newArrayList(elements)); 443 } 444 445 /** 446 * Returns an Iterator that walks the specified array, nulling out elements behind it. This can 447 * avoid memory leaks when an element is no longer necessary. 448 * 449 * <p>This is mainly just to avoid the intermediate ArrayDeque in ConsumingQueueIterator. 450 */ 451 private static <T> Iterator<T> consumingForArray(final T... elements) { 452 return new UnmodifiableIterator<T>() { 453 int index = 0; 454 455 @Override 456 public boolean hasNext() { 457 return index < elements.length; 458 } 459 460 @Override 461 public T next() { 462 if (!hasNext()) { 463 throw new NoSuchElementException(); 464 } 465 T result = elements[index]; 466 elements[index] = null; 467 index++; 468 return result; 469 } 470 }; 471 } 472 473 /** 474 * Combines two iterators into a single iterator. The returned iterator iterates across the 475 * elements in {@code a}, followed by the elements in {@code b}. The source iterators are not 476 * polled until necessary. 477 * 478 * <p>The returned iterator supports {@code remove()} when the corresponding input iterator 479 * supports it. 480 */ 481 public static <T> Iterator<T> concat(Iterator<? extends T> a, Iterator<? extends T> b) { 482 checkNotNull(a); 483 checkNotNull(b); 484 return concat(consumingForArray(a, b)); 485 } 486 487 /** 488 * Combines three iterators into a single iterator. The returned iterator iterates across the 489 * elements in {@code a}, followed by the elements in {@code b}, followed by the elements in 490 * {@code c}. The source iterators are not polled until necessary. 491 * 492 * <p>The returned iterator supports {@code remove()} when the corresponding input iterator 493 * supports it. 494 */ 495 public static <T> Iterator<T> concat( 496 Iterator<? extends T> a, Iterator<? extends T> b, Iterator<? extends T> c) { 497 checkNotNull(a); 498 checkNotNull(b); 499 checkNotNull(c); 500 return concat(consumingForArray(a, b, c)); 501 } 502 503 /** 504 * Combines four iterators into a single iterator. The returned iterator iterates across the 505 * elements in {@code a}, followed by the elements in {@code b}, followed by the elements in 506 * {@code c}, followed by the elements in {@code d}. The source iterators are not polled until 507 * necessary. 508 * 509 * <p>The returned iterator supports {@code remove()} when the corresponding input iterator 510 * supports it. 511 */ 512 public static <T> Iterator<T> concat( 513 Iterator<? extends T> a, 514 Iterator<? extends T> b, 515 Iterator<? extends T> c, 516 Iterator<? extends T> d) { 517 checkNotNull(a); 518 checkNotNull(b); 519 checkNotNull(c); 520 checkNotNull(d); 521 return concat(consumingForArray(a, b, c, d)); 522 } 523 524 /** 525 * Combines multiple iterators into a single iterator. The returned iterator iterates across the 526 * elements of each iterator in {@code inputs}. The input iterators are not polled until 527 * necessary. 528 * 529 * <p>The returned iterator supports {@code remove()} when the corresponding input iterator 530 * supports it. 531 * 532 * @throws NullPointerException if any of the provided iterators is null 533 */ 534 public static <T> Iterator<T> concat(Iterator<? extends T>... inputs) { 535 return concatNoDefensiveCopy(Arrays.copyOf(inputs, inputs.length)); 536 } 537 538 /** 539 * Combines multiple iterators into a single iterator. The returned iterator iterates across the 540 * elements of each iterator in {@code inputs}. The input iterators are not polled until 541 * necessary. 542 * 543 * <p>The returned iterator supports {@code remove()} when the corresponding input iterator 544 * supports it. The methods of the returned iterator may throw {@code NullPointerException} if any 545 * of the input iterators is null. 546 */ 547 public static <T> Iterator<T> concat(Iterator<? extends Iterator<? extends T>> inputs) { 548 return new ConcatenatedIterator<T>(inputs); 549 } 550 551 /** Concats a varargs array of iterators without making a defensive copy of the array. */ 552 static <T> Iterator<T> concatNoDefensiveCopy(Iterator<? extends T>... inputs) { 553 for (Iterator<? extends T> input : checkNotNull(inputs)) { 554 checkNotNull(input); 555 } 556 return concat(consumingForArray(inputs)); 557 } 558 559 /** 560 * Divides an iterator into unmodifiable sublists of the given size (the final list may be 561 * smaller). For example, partitioning an iterator containing {@code [a, b, c, d, e]} with a 562 * partition size of 3 yields {@code [[a, b, c], [d, e]]} -- an outer iterator containing two 563 * inner lists of three and two elements, all in the original order. 564 * 565 * <p>The returned lists implement {@link java.util.RandomAccess}. 566 * 567 * @param iterator the iterator to return a partitioned view of 568 * @param size the desired size of each partition (the last may be smaller) 569 * @return an iterator of immutable lists containing the elements of {@code iterator} divided into 570 * partitions 571 * @throws IllegalArgumentException if {@code size} is nonpositive 572 */ 573 public static <T> UnmodifiableIterator<List<T>> partition(Iterator<T> iterator, int size) { 574 return partitionImpl(iterator, size, false); 575 } 576 577 /** 578 * Divides an iterator into unmodifiable sublists of the given size, padding the final iterator 579 * with null values if necessary. For example, partitioning an iterator containing {@code [a, b, 580 * c, d, e]} with a partition size of 3 yields {@code [[a, b, c], [d, e, null]]} -- an outer 581 * iterator containing two inner lists of three elements each, all in the original order. 582 * 583 * <p>The returned lists implement {@link java.util.RandomAccess}. 584 * 585 * @param iterator the iterator to return a partitioned view of 586 * @param size the desired size of each partition 587 * @return an iterator of immutable lists containing the elements of {@code iterator} divided into 588 * partitions (the final iterable may have trailing null elements) 589 * @throws IllegalArgumentException if {@code size} is nonpositive 590 */ 591 public static <T> UnmodifiableIterator<List<T>> paddedPartition(Iterator<T> iterator, int size) { 592 return partitionImpl(iterator, size, true); 593 } 594 595 private static <T> UnmodifiableIterator<List<T>> partitionImpl( 596 final Iterator<T> iterator, final int size, final boolean pad) { 597 checkNotNull(iterator); 598 checkArgument(size > 0); 599 return new UnmodifiableIterator<List<T>>() { 600 @Override 601 public boolean hasNext() { 602 return iterator.hasNext(); 603 } 604 605 @Override 606 public List<T> next() { 607 if (!hasNext()) { 608 throw new NoSuchElementException(); 609 } 610 Object[] array = new Object[size]; 611 int count = 0; 612 for (; count < size && iterator.hasNext(); count++) { 613 array[count] = iterator.next(); 614 } 615 for (int i = count; i < size; i++) { 616 array[i] = null; // for GWT 617 } 618 619 @SuppressWarnings("unchecked") // we only put Ts in it 620 List<T> list = Collections.unmodifiableList((List<T>) Arrays.asList(array)); 621 return (pad || count == size) ? list : list.subList(0, count); 622 } 623 }; 624 } 625 626 /** 627 * Returns a view of {@code unfiltered} containing all elements that satisfy the input predicate 628 * {@code retainIfTrue}. 629 */ 630 public static <T> UnmodifiableIterator<T> filter( 631 final Iterator<T> unfiltered, final Predicate<? super T> retainIfTrue) { 632 checkNotNull(unfiltered); 633 checkNotNull(retainIfTrue); 634 return new AbstractIterator<T>() { 635 @Override 636 protected T computeNext() { 637 while (unfiltered.hasNext()) { 638 T element = unfiltered.next(); 639 if (retainIfTrue.apply(element)) { 640 return element; 641 } 642 } 643 return endOfData(); 644 } 645 }; 646 } 647 648 /** 649 * Returns a view of {@code unfiltered} containing all elements that are of the type {@code 650 * desiredType}. 651 */ 652 @SuppressWarnings("unchecked") // can cast to <T> because non-Ts are removed 653 @GwtIncompatible // Class.isInstance 654 public static <T> UnmodifiableIterator<T> filter(Iterator<?> unfiltered, Class<T> desiredType) { 655 return (UnmodifiableIterator<T>) filter(unfiltered, instanceOf(desiredType)); 656 } 657 658 /** 659 * Returns {@code true} if one or more elements returned by {@code iterator} satisfy the given 660 * predicate. 661 */ 662 public static <T> boolean any(Iterator<T> iterator, Predicate<? super T> predicate) { 663 return indexOf(iterator, predicate) != -1; 664 } 665 666 /** 667 * Returns {@code true} if every element returned by {@code iterator} satisfies the given 668 * predicate. If {@code iterator} is empty, {@code true} is returned. 669 */ 670 public static <T> boolean all(Iterator<T> iterator, Predicate<? super T> predicate) { 671 checkNotNull(predicate); 672 while (iterator.hasNext()) { 673 T element = iterator.next(); 674 if (!predicate.apply(element)) { 675 return false; 676 } 677 } 678 return true; 679 } 680 681 /** 682 * Returns the first element in {@code iterator} that satisfies the given predicate; use this 683 * method only when such an element is known to exist. If no such element is found, the iterator 684 * will be left exhausted: its {@code hasNext()} method will return {@code false}. If it is 685 * possible that <i>no</i> element will match, use {@link #tryFind} or {@link #find(Iterator, 686 * Predicate, Object)} instead. 687 * 688 * @throws NoSuchElementException if no element in {@code iterator} matches the given predicate 689 */ 690 public static <T> T find(Iterator<T> iterator, Predicate<? super T> predicate) { 691 checkNotNull(iterator); 692 checkNotNull(predicate); 693 while (iterator.hasNext()) { 694 T t = iterator.next(); 695 if (predicate.apply(t)) { 696 return t; 697 } 698 } 699 throw new NoSuchElementException(); 700 } 701 702 /** 703 * Returns the first element in {@code iterator} that satisfies the given predicate. If no such 704 * element is found, {@code defaultValue} will be returned from this method and the iterator will 705 * be left exhausted: its {@code hasNext()} method will return {@code false}. Note that this can 706 * usually be handled more naturally using {@code tryFind(iterator, predicate).or(defaultValue)}. 707 * 708 * @since 7.0 709 */ 710 public static <T> @Nullable T find( 711 Iterator<? extends T> iterator, Predicate<? super T> predicate, @Nullable T defaultValue) { 712 checkNotNull(iterator); 713 checkNotNull(predicate); 714 while (iterator.hasNext()) { 715 T t = iterator.next(); 716 if (predicate.apply(t)) { 717 return t; 718 } 719 } 720 return defaultValue; 721 } 722 723 /** 724 * Returns an {@link Optional} containing the first element in {@code iterator} that satisfies the 725 * given predicate, if such an element exists. If no such element is found, an empty {@link 726 * Optional} will be returned from this method and the iterator will be left exhausted: its {@code 727 * hasNext()} method will return {@code false}. 728 * 729 * <p><b>Warning:</b> avoid using a {@code predicate} that matches {@code null}. If {@code null} 730 * is matched in {@code iterator}, a NullPointerException will be thrown. 731 * 732 * @since 11.0 733 */ 734 public static <T> Optional<T> tryFind(Iterator<T> iterator, Predicate<? super T> predicate) { 735 checkNotNull(iterator); 736 checkNotNull(predicate); 737 while (iterator.hasNext()) { 738 T t = iterator.next(); 739 if (predicate.apply(t)) { 740 return Optional.of(t); 741 } 742 } 743 return Optional.absent(); 744 } 745 746 /** 747 * Returns the index in {@code iterator} of the first element that satisfies the provided {@code 748 * predicate}, or {@code -1} if the Iterator has no such elements. 749 * 750 * <p>More formally, returns the lowest index {@code i} such that {@code 751 * predicate.apply(Iterators.get(iterator, i))} returns {@code true}, or {@code -1} if there is no 752 * such index. 753 * 754 * <p>If -1 is returned, the iterator will be left exhausted: its {@code hasNext()} method will 755 * return {@code false}. Otherwise, the iterator will be set to the element which satisfies the 756 * {@code predicate}. 757 * 758 * @since 2.0 759 */ 760 public static <T> int indexOf(Iterator<T> iterator, Predicate<? super T> predicate) { 761 checkNotNull(predicate, "predicate"); 762 for (int i = 0; iterator.hasNext(); i++) { 763 T current = iterator.next(); 764 if (predicate.apply(current)) { 765 return i; 766 } 767 } 768 return -1; 769 } 770 771 /** 772 * Returns a view containing the result of applying {@code function} to each element of {@code 773 * fromIterator}. 774 * 775 * <p>The returned iterator supports {@code remove()} if {@code fromIterator} does. After a 776 * successful {@code remove()} call, {@code fromIterator} no longer contains the corresponding 777 * element. 778 */ 779 public static <F, T> Iterator<T> transform( 780 final Iterator<F> fromIterator, final Function<? super F, ? extends T> function) { 781 checkNotNull(function); 782 return new TransformedIterator<F, T>(fromIterator) { 783 @Override 784 T transform(F from) { 785 return function.apply(from); 786 } 787 }; 788 } 789 790 /** 791 * Advances {@code iterator} {@code position + 1} times, returning the element at the {@code 792 * position}th position. 793 * 794 * @param position position of the element to return 795 * @return the element at the specified position in {@code iterator} 796 * @throws IndexOutOfBoundsException if {@code position} is negative or greater than or equal to 797 * the number of elements remaining in {@code iterator} 798 */ 799 public static <T> T get(Iterator<T> iterator, int position) { 800 checkNonnegative(position); 801 int skipped = advance(iterator, position); 802 if (!iterator.hasNext()) { 803 throw new IndexOutOfBoundsException( 804 "position (" 805 + position 806 + ") must be less than the number of elements that remained (" 807 + skipped 808 + ")"); 809 } 810 return iterator.next(); 811 } 812 813 /** 814 * Advances {@code iterator} {@code position + 1} times, returning the element at the {@code 815 * position}th position or {@code defaultValue} otherwise. 816 * 817 * @param position position of the element to return 818 * @param defaultValue the default value to return if the iterator is empty or if {@code position} 819 * is greater than the number of elements remaining in {@code iterator} 820 * @return the element at the specified position in {@code iterator} or {@code defaultValue} if 821 * {@code iterator} produces fewer than {@code position + 1} elements. 822 * @throws IndexOutOfBoundsException if {@code position} is negative 823 * @since 4.0 824 */ 825 public static <T> @Nullable T get( 826 Iterator<? extends T> iterator, int position, @Nullable T defaultValue) { 827 checkNonnegative(position); 828 advance(iterator, position); 829 return getNext(iterator, defaultValue); 830 } 831 832 static void checkNonnegative(int position) { 833 if (position < 0) { 834 throw new IndexOutOfBoundsException("position (" + position + ") must not be negative"); 835 } 836 } 837 838 /** 839 * Returns the next element in {@code iterator} or {@code defaultValue} if the iterator is empty. 840 * The {@link Iterables} analog to this method is {@link Iterables#getFirst}. 841 * 842 * @param defaultValue the default value to return if the iterator is empty 843 * @return the next element of {@code iterator} or the default value 844 * @since 7.0 845 */ 846 public static <T> @Nullable T getNext(Iterator<? extends T> iterator, @Nullable T defaultValue) { 847 return iterator.hasNext() ? iterator.next() : defaultValue; 848 } 849 850 /** 851 * Advances {@code iterator} to the end, returning the last element. 852 * 853 * @return the last element of {@code iterator} 854 * @throws NoSuchElementException if the iterator is empty 855 */ 856 public static <T> T getLast(Iterator<T> iterator) { 857 while (true) { 858 T current = iterator.next(); 859 if (!iterator.hasNext()) { 860 return current; 861 } 862 } 863 } 864 865 /** 866 * Advances {@code iterator} to the end, returning the last element or {@code defaultValue} if the 867 * iterator is empty. 868 * 869 * @param defaultValue the default value to return if the iterator is empty 870 * @return the last element of {@code iterator} 871 * @since 3.0 872 */ 873 public static <T> @Nullable T getLast(Iterator<? extends T> iterator, @Nullable T defaultValue) { 874 return iterator.hasNext() ? getLast(iterator) : defaultValue; 875 } 876 877 /** 878 * Calls {@code next()} on {@code iterator}, either {@code numberToAdvance} times or until {@code 879 * hasNext()} returns {@code false}, whichever comes first. 880 * 881 * @return the number of elements the iterator was advanced 882 * @since 13.0 (since 3.0 as {@code Iterators.skip}) 883 */ 884 @CanIgnoreReturnValue 885 public static int advance(Iterator<?> iterator, int numberToAdvance) { 886 checkNotNull(iterator); 887 checkArgument(numberToAdvance >= 0, "numberToAdvance must be nonnegative"); 888 889 int i; 890 for (i = 0; i < numberToAdvance && iterator.hasNext(); i++) { 891 iterator.next(); 892 } 893 return i; 894 } 895 896 /** 897 * Returns a view containing the first {@code limitSize} elements of {@code iterator}. If {@code 898 * iterator} contains fewer than {@code limitSize} elements, the returned view contains all of its 899 * elements. The returned iterator supports {@code remove()} if {@code iterator} does. 900 * 901 * @param iterator the iterator 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> Iterator<T> limit(final Iterator<T> iterator, final int limitSize) { 907 checkNotNull(iterator); 908 checkArgument(limitSize >= 0, "limit is negative"); 909 return new Iterator<T>() { 910 private int count; 911 912 @Override 913 public boolean hasNext() { 914 return count < limitSize && iterator.hasNext(); 915 } 916 917 @Override 918 public T next() { 919 if (!hasNext()) { 920 throw new NoSuchElementException(); 921 } 922 count++; 923 return iterator.next(); 924 } 925 926 @Override 927 public void remove() { 928 iterator.remove(); 929 } 930 }; 931 } 932 933 /** 934 * Returns a view of the supplied {@code iterator} that removes each element from the supplied 935 * {@code iterator} as it is returned. 936 * 937 * <p>The provided iterator must support {@link Iterator#remove()} or else the returned iterator 938 * will fail on the first call to {@code next}. 939 * 940 * @param iterator the iterator to remove and return elements from 941 * @return an iterator that removes and returns elements from the supplied iterator 942 * @since 2.0 943 */ 944 public static <T> Iterator<T> consumingIterator(final Iterator<T> iterator) { 945 checkNotNull(iterator); 946 return new UnmodifiableIterator<T>() { 947 @Override 948 public boolean hasNext() { 949 return iterator.hasNext(); 950 } 951 952 @Override 953 public T next() { 954 T next = iterator.next(); 955 iterator.remove(); 956 return next; 957 } 958 959 @Override 960 public String toString() { 961 return "Iterators.consumingIterator(...)"; 962 } 963 }; 964 } 965 966 /** 967 * Deletes and returns the next value from the iterator, or returns {@code null} if there is no 968 * such value. 969 */ 970 static <T> @Nullable T pollNext(Iterator<T> iterator) { 971 if (iterator.hasNext()) { 972 T result = iterator.next(); 973 iterator.remove(); 974 return result; 975 } else { 976 return null; 977 } 978 } 979 980 // Methods only in Iterators, not in Iterables 981 982 /** Clears the iterator using its remove method. */ 983 static void clear(Iterator<?> iterator) { 984 checkNotNull(iterator); 985 while (iterator.hasNext()) { 986 iterator.next(); 987 iterator.remove(); 988 } 989 } 990 991 /** 992 * Returns an iterator containing the elements of {@code array} in order. The returned iterator is 993 * a view of the array; subsequent changes to the array will be reflected in the iterator. 994 * 995 * <p><b>Note:</b> It is often preferable to represent your data using a collection type, for 996 * example using {@link Arrays#asList(Object[])}, making this method unnecessary. 997 * 998 * <p>The {@code Iterable} equivalent of this method is either {@link Arrays#asList(Object[])}, 999 * {@link ImmutableList#copyOf(Object[])}}, or {@link ImmutableList#of}. 1000 */ 1001 @SafeVarargs 1002 public static <T> UnmodifiableIterator<T> forArray(final T... array) { 1003 return forArray(array, 0, array.length, 0); 1004 } 1005 1006 /** 1007 * Returns a list iterator containing the elements in the specified range of {@code array} in 1008 * order, starting at the specified index. 1009 * 1010 * <p>The {@code Iterable} equivalent of this method is {@code 1011 * Arrays.asList(array).subList(offset, offset + length).listIterator(index)}. 1012 */ 1013 static <T> UnmodifiableListIterator<T> forArray( 1014 final T[] array, final int offset, int length, int index) { 1015 checkArgument(length >= 0); 1016 int end = offset + length; 1017 1018 // Technically we should give a slightly more descriptive error on overflow 1019 Preconditions.checkPositionIndexes(offset, end, array.length); 1020 Preconditions.checkPositionIndex(index, length); 1021 if (length == 0) { 1022 return emptyListIterator(); 1023 } 1024 return new ArrayItr<T>(array, offset, length, index); 1025 } 1026 1027 private static final class ArrayItr<T> extends AbstractIndexedListIterator<T> { 1028 static final UnmodifiableListIterator<Object> EMPTY = new ArrayItr<>(new Object[0], 0, 0, 0); 1029 1030 private final T[] array; 1031 private final int offset; 1032 1033 ArrayItr(T[] array, int offset, int length, int index) { 1034 super(length, index); 1035 this.array = array; 1036 this.offset = offset; 1037 } 1038 1039 @Override 1040 protected T get(int index) { 1041 return array[offset + index]; 1042 } 1043 } 1044 1045 /** 1046 * Returns an iterator containing only {@code value}. 1047 * 1048 * <p>The {@link Iterable} equivalent of this method is {@link Collections#singleton}. 1049 */ 1050 public static <T> UnmodifiableIterator<T> singletonIterator(final @Nullable T value) { 1051 return new UnmodifiableIterator<T>() { 1052 boolean done; 1053 1054 @Override 1055 public boolean hasNext() { 1056 return !done; 1057 } 1058 1059 @Override 1060 public T next() { 1061 if (done) { 1062 throw new NoSuchElementException(); 1063 } 1064 done = true; 1065 return value; 1066 } 1067 }; 1068 } 1069 1070 /** 1071 * Adapts an {@code Enumeration} to the {@code Iterator} interface. 1072 * 1073 * <p>This method has no equivalent in {@link Iterables} because viewing an {@code Enumeration} as 1074 * an {@code Iterable} is impossible. However, the contents can be <i>copied</i> into a collection 1075 * using {@link Collections#list}. 1076 */ 1077 public static <T> UnmodifiableIterator<T> forEnumeration(final Enumeration<T> enumeration) { 1078 checkNotNull(enumeration); 1079 return new UnmodifiableIterator<T>() { 1080 @Override 1081 public boolean hasNext() { 1082 return enumeration.hasMoreElements(); 1083 } 1084 1085 @Override 1086 public T next() { 1087 return enumeration.nextElement(); 1088 } 1089 }; 1090 } 1091 1092 /** 1093 * Adapts an {@code Iterator} to the {@code Enumeration} interface. 1094 * 1095 * <p>The {@code Iterable} equivalent of this method is either {@link Collections#enumeration} (if 1096 * you have a {@link Collection}), or {@code Iterators.asEnumeration(collection.iterator())}. 1097 */ 1098 public static <T> Enumeration<T> asEnumeration(final Iterator<T> iterator) { 1099 checkNotNull(iterator); 1100 return new Enumeration<T>() { 1101 @Override 1102 public boolean hasMoreElements() { 1103 return iterator.hasNext(); 1104 } 1105 1106 @Override 1107 public T nextElement() { 1108 return iterator.next(); 1109 } 1110 }; 1111 } 1112 1113 /** Implementation of PeekingIterator that avoids peeking unless necessary. */ 1114 private static class PeekingImpl<E> implements PeekingIterator<E> { 1115 1116 private final Iterator<? extends E> iterator; 1117 private boolean hasPeeked; 1118 private @Nullable E peekedElement; 1119 1120 public PeekingImpl(Iterator<? extends E> iterator) { 1121 this.iterator = checkNotNull(iterator); 1122 } 1123 1124 @Override 1125 public boolean hasNext() { 1126 return hasPeeked || iterator.hasNext(); 1127 } 1128 1129 @Override 1130 public E next() { 1131 if (!hasPeeked) { 1132 return iterator.next(); 1133 } 1134 E result = peekedElement; 1135 hasPeeked = false; 1136 peekedElement = null; 1137 return result; 1138 } 1139 1140 @Override 1141 public void remove() { 1142 checkState(!hasPeeked, "Can't remove after you've peeked at next"); 1143 iterator.remove(); 1144 } 1145 1146 @Override 1147 public E peek() { 1148 if (!hasPeeked) { 1149 peekedElement = iterator.next(); 1150 hasPeeked = true; 1151 } 1152 return peekedElement; 1153 } 1154 } 1155 1156 /** 1157 * Returns a {@code PeekingIterator} backed by the given iterator. 1158 * 1159 * <p>Calls to the {@code peek} method with no intervening calls to {@code next} do not affect the 1160 * iteration, and hence return the same object each time. A subsequent call to {@code next} is 1161 * guaranteed to return the same object again. For example: 1162 * 1163 * <pre>{@code 1164 * PeekingIterator<String> peekingIterator = 1165 * Iterators.peekingIterator(Iterators.forArray("a", "b")); 1166 * String a1 = peekingIterator.peek(); // returns "a" 1167 * String a2 = peekingIterator.peek(); // also returns "a" 1168 * String a3 = peekingIterator.next(); // also returns "a" 1169 * }</pre> 1170 * 1171 * <p>Any structural changes to the underlying iteration (aside from those performed by the 1172 * iterator's own {@link PeekingIterator#remove()} method) will leave the iterator in an undefined 1173 * state. 1174 * 1175 * <p>The returned iterator does not support removal after peeking, as explained by {@link 1176 * PeekingIterator#remove()}. 1177 * 1178 * <p>Note: If the given iterator is already a {@code PeekingIterator}, it <i>might</i> be 1179 * returned to the caller, although this is neither guaranteed to occur nor required to be 1180 * consistent. For example, this method <i>might</i> choose to pass through recognized 1181 * implementations of {@code PeekingIterator} when the behavior of the implementation is known to 1182 * meet the contract guaranteed by this method. 1183 * 1184 * <p>There is no {@link Iterable} equivalent to this method, so use this method to wrap each 1185 * individual iterator as it is generated. 1186 * 1187 * @param iterator the backing iterator. The {@link PeekingIterator} assumes ownership of this 1188 * iterator, so users should cease making direct calls to it after calling this method. 1189 * @return a peeking iterator backed by that iterator. Apart from the additional {@link 1190 * PeekingIterator#peek()} method, this iterator behaves exactly the same as {@code iterator}. 1191 */ 1192 public static <T> PeekingIterator<T> peekingIterator(Iterator<? extends T> iterator) { 1193 if (iterator instanceof PeekingImpl) { 1194 // Safe to cast <? extends T> to <T> because PeekingImpl only uses T 1195 // covariantly (and cannot be subclassed to add non-covariant uses). 1196 @SuppressWarnings("unchecked") 1197 PeekingImpl<T> peeking = (PeekingImpl<T>) iterator; 1198 return peeking; 1199 } 1200 return new PeekingImpl<T>(iterator); 1201 } 1202 1203 /** 1204 * Simply returns its argument. 1205 * 1206 * @deprecated no need to use this 1207 * @since 10.0 1208 */ 1209 @Deprecated 1210 public static <T> PeekingIterator<T> peekingIterator(PeekingIterator<T> iterator) { 1211 return checkNotNull(iterator); 1212 } 1213 1214 /** 1215 * Returns an iterator over the merged contents of all given {@code iterators}, traversing every 1216 * element of the input iterators. Equivalent entries will not be de-duplicated. 1217 * 1218 * <p>Callers must ensure that the source {@code iterators} are in non-descending order as this 1219 * method does not sort its input. 1220 * 1221 * <p>For any equivalent elements across all {@code iterators}, it is undefined which element is 1222 * returned first. 1223 * 1224 * @since 11.0 1225 */ 1226 @Beta 1227 public static <T> UnmodifiableIterator<T> mergeSorted( 1228 Iterable<? extends Iterator<? extends T>> iterators, Comparator<? super T> comparator) { 1229 checkNotNull(iterators, "iterators"); 1230 checkNotNull(comparator, "comparator"); 1231 1232 return new MergingIterator<T>(iterators, comparator); 1233 } 1234 1235 /** 1236 * An iterator that performs a lazy N-way merge, calculating the next value each time the iterator 1237 * is polled. This amortizes the sorting cost over the iteration and requires less memory than 1238 * sorting all elements at once. 1239 * 1240 * <p>Retrieving a single element takes approximately O(log(M)) time, where M is the number of 1241 * iterators. (Retrieving all elements takes approximately O(N*log(M)) time, where N is the total 1242 * number of elements.) 1243 */ 1244 private static class MergingIterator<T> extends UnmodifiableIterator<T> { 1245 final Queue<PeekingIterator<T>> queue; 1246 1247 public MergingIterator( 1248 Iterable<? extends Iterator<? extends T>> iterators, 1249 final Comparator<? super T> itemComparator) { 1250 // A comparator that's used by the heap, allowing the heap 1251 // to be sorted based on the top of each iterator. 1252 Comparator<PeekingIterator<T>> heapComparator = 1253 new Comparator<PeekingIterator<T>>() { 1254 @Override 1255 public int compare(PeekingIterator<T> o1, PeekingIterator<T> o2) { 1256 return itemComparator.compare(o1.peek(), o2.peek()); 1257 } 1258 }; 1259 1260 queue = new PriorityQueue<>(2, heapComparator); 1261 1262 for (Iterator<? extends T> iterator : iterators) { 1263 if (iterator.hasNext()) { 1264 queue.add(Iterators.peekingIterator(iterator)); 1265 } 1266 } 1267 } 1268 1269 @Override 1270 public boolean hasNext() { 1271 return !queue.isEmpty(); 1272 } 1273 1274 @Override 1275 public T next() { 1276 PeekingIterator<T> nextIter = queue.remove(); 1277 T next = nextIter.next(); 1278 if (nextIter.hasNext()) { 1279 queue.add(nextIter); 1280 } 1281 return next; 1282 } 1283 } 1284 1285 private static class ConcatenatedIterator<T> implements Iterator<T> { 1286 /* The last iterator to return an element. Calls to remove() go to this iterator. */ 1287 private @Nullable Iterator<? extends T> toRemove; 1288 1289 /* The iterator currently returning elements. */ 1290 private Iterator<? extends T> iterator; 1291 1292 /* 1293 * We track the "meta iterators," the iterators-of-iterators, below. Usually, topMetaIterator 1294 * is the only one in use, but if we encounter nested concatenations, we start a deque of 1295 * meta-iterators rather than letting the nesting get arbitrarily deep. This keeps each 1296 * operation O(1). 1297 */ 1298 1299 private Iterator<? extends Iterator<? extends T>> topMetaIterator; 1300 1301 // Only becomes nonnull if we encounter nested concatenations. 1302 private @Nullable Deque<Iterator<? extends Iterator<? extends T>>> metaIterators; 1303 1304 ConcatenatedIterator(Iterator<? extends Iterator<? extends T>> metaIterator) { 1305 iterator = emptyIterator(); 1306 topMetaIterator = checkNotNull(metaIterator); 1307 } 1308 1309 // Returns a nonempty meta-iterator or, if all meta-iterators are empty, null. 1310 private @Nullable Iterator<? extends Iterator<? extends T>> getTopMetaIterator() { 1311 while (topMetaIterator == null || !topMetaIterator.hasNext()) { 1312 if (metaIterators != null && !metaIterators.isEmpty()) { 1313 topMetaIterator = metaIterators.removeFirst(); 1314 } else { 1315 return null; 1316 } 1317 } 1318 return topMetaIterator; 1319 } 1320 1321 @Override 1322 public boolean hasNext() { 1323 while (!checkNotNull(iterator).hasNext()) { 1324 // this weird checkNotNull positioning appears required by our tests, which expect 1325 // both hasNext and next to throw NPE if an input iterator is null. 1326 1327 topMetaIterator = getTopMetaIterator(); 1328 if (topMetaIterator == null) { 1329 return false; 1330 } 1331 1332 iterator = topMetaIterator.next(); 1333 1334 if (iterator instanceof ConcatenatedIterator) { 1335 // Instead of taking linear time in the number of nested concatenations, unpack 1336 // them into the queue 1337 @SuppressWarnings("unchecked") 1338 ConcatenatedIterator<T> topConcat = (ConcatenatedIterator<T>) iterator; 1339 iterator = topConcat.iterator; 1340 1341 // topConcat.topMetaIterator, then topConcat.metaIterators, then this.topMetaIterator, 1342 // then this.metaIterators 1343 1344 if (this.metaIterators == null) { 1345 this.metaIterators = new ArrayDeque<>(); 1346 } 1347 this.metaIterators.addFirst(this.topMetaIterator); 1348 if (topConcat.metaIterators != null) { 1349 while (!topConcat.metaIterators.isEmpty()) { 1350 this.metaIterators.addFirst(topConcat.metaIterators.removeLast()); 1351 } 1352 } 1353 this.topMetaIterator = topConcat.topMetaIterator; 1354 } 1355 } 1356 return true; 1357 } 1358 1359 @Override 1360 public T next() { 1361 if (hasNext()) { 1362 toRemove = iterator; 1363 return iterator.next(); 1364 } else { 1365 throw new NoSuchElementException(); 1366 } 1367 } 1368 1369 @Override 1370 public void remove() { 1371 CollectPreconditions.checkRemove(toRemove != null); 1372 toRemove.remove(); 1373 toRemove = null; 1374 } 1375 } 1376 1377 /** Used to avoid http://bugs.sun.com/view_bug.do?bug_id=6558557 */ 1378 static <T> ListIterator<T> cast(Iterator<T> iterator) { 1379 return (ListIterator<T>) iterator; 1380 } 1381}