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