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