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