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