Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
   /*
    * Copyright (C) 2007 The Guava Authors
    *
    * Licensed under the Apache License, Version 2.0 (the "License");
    * you may not use this file except in compliance with the License.
    * You may obtain a copy of the License at
    *
    * http://www.apache.org/licenses/LICENSE-2.0
    *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   */
  
  package com.google.common.collect;
  
  import static com.google.common.base.Preconditions.checkArgument;
  import static com.google.common.base.Preconditions.checkNotNull;
  import static com.google.common.base.Preconditions.checkState;
  import static com.google.common.base.Predicates.equalTo;
  import static com.google.common.base.Predicates.in;
  import static com.google.common.base.Predicates.not;
  import static com.google.common.collect.CollectPreconditions.checkRemove;
  
  
  import java.util.Arrays;
  import java.util.List;
  import java.util.Queue;
  
This class contains static utility methods that operate on or return objects of type java.util.Iterator. Except as noted, each method has a corresponding java.lang.Iterable-based method in the Iterables class.

Performance notes: Unless otherwise noted, all of the iterators produced in this class are lazy, which means that they only advance the backing iteration when absolutely necessary.

See the Guava User Guide section on Iterators.

Author(s):
Kevin Bourrillion
Jared Levy
Since:
2.0 (imported from Google Collections Library)
  
  @GwtCompatible(emulated = true)
  public final class Iterators {
    private Iterators() {}
  
        = new UnmodifiableListIterator<Object>() {
          @Override
          public boolean hasNext() {
            return false;
          }
          @Override
          public Object next() {
            throw new NoSuchElementException();
          }
          @Override
          public boolean hasPrevious() {
            return false;
          }
          @Override
          public Object previous() {
            throw new NoSuchElementException();
          }
          @Override
          public int nextIndex() {
            return 0;
          }
          @Override
          public int previousIndex() {
            return -1;
          }
        };

  
Returns the empty iterator.

The java.lang.Iterable equivalent of this method is ImmutableSet.of().

 
   public static <T> UnmodifiableIterator<T> emptyIterator() {
     return emptyListIterator();
   }

  
Returns the empty iterator.

The java.lang.Iterable equivalent of this method is ImmutableSet.of().

 
   // Casting to any type is safe since there are no actual elements.
   @SuppressWarnings("unchecked")
   }
 
   private static final Iterator<ObjectEMPTY_MODIFIABLE_ITERATOR =
       new Iterator<Object>() {
         @Override public boolean hasNext() {
           return false;
         }
 
         @Override public Object next() {
           throw new NoSuchElementException();
         }
 
         @Override public void remove() {
           checkRemove(false);
         }
       };

  
Returns the empty Iterator that throws java.lang.IllegalStateException instead of java.lang.UnsupportedOperationException on a call to java.util.Iterator.remove().
 
   // Casting to any type is safe since there are no actual elements.
   @SuppressWarnings("unchecked")
   static <T> Iterator<T> emptyModifiableIterator() {
     return (Iterator<T>) ;
   }

  
Returns an unmodifiable view of iterator.
 
   public static <T> UnmodifiableIterator<T> unmodifiableIterator(
       final Iterator<T> iterator) {
     checkNotNull(iterator);
     if (iterator instanceof UnmodifiableIterator) {
       return (UnmodifiableIterator<T>) iterator;
     }
     return new UnmodifiableIterator<T>() {
       @Override
       public boolean hasNext() {
         return iterator.hasNext();
       }
       @Override
       public T next() {
         return iterator.next();
       }
     };
   }

  
Simply returns its argument.

Deprecated:
no need to use this
Since:
10.0
 
   @Deprecated public static <T> UnmodifiableIterator<T> unmodifiableIterator(
       UnmodifiableIterator<T> iterator) {
     return checkNotNull(iterator);
   }

  
Returns the number of elements remaining in iterator. The iterator will be left exhausted: its hasNext() method will return false.
 
   public static int size(Iterator<?> iterator) {
     int count = 0;
     while (iterator.hasNext()) {
       iterator.next();
       count++;
     }
     return count;
   }

  
Returns true if iterator contains element.
 
   public static boolean contains(Iterator<?> iterator, @Nullable Object element) {
     return any(iteratorequalTo(element));
   }

  
Traverses an iterator and removes every element that belongs to the provided collection. The iterator will be left exhausted: its hasNext() method will return false.

Parameters:
removeFrom the iterator to (potentially) remove elements from
elementsToRemove the elements to remove
Returns:
true if any element was removed from iterator
 
   public static boolean removeAll(
       Iterator<?> removeFromCollection<?> elementsToRemove) {
     return removeIf(removeFromin(elementsToRemove));
   }

  
Removes every element that satisfies the provided predicate from the iterator. The iterator will be left exhausted: its hasNext() method will return false.

Parameters:
removeFrom the iterator to (potentially) remove elements from
predicate a predicate that determines whether an element should be removed
Returns:
true if any elements were removed from the iterator
Since:
2.0
 
   public static <T> boolean removeIf(
       Iterator<T> removeFromPredicate<? super T> predicate) {
     checkNotNull(predicate);
     boolean modified = false;
     while (removeFrom.hasNext()) {
       if (predicate.apply(removeFrom.next())) {
         removeFrom.remove();
         modified = true;
       }
     }
     return modified;
   }

  
Traverses an iterator and removes every element that does not belong to the provided collection. The iterator will be left exhausted: its hasNext() method will return false.

Parameters:
removeFrom the iterator to (potentially) remove elements from
elementsToRetain the elements to retain
Returns:
true if any element was removed from iterator
 
   public static boolean retainAll(
       Iterator<?> removeFromCollection<?> elementsToRetain) {
     return removeIf(removeFromnot(in(elementsToRetain)));
   }

  
Determines whether two iterators contain equal elements in the same order. More specifically, this method returns true if iterator1 and iterator2 contain the same number of elements and every element of iterator1 is equal to the corresponding element of iterator2.

Note that this will modify the supplied iterators, since they will have been advanced some number of elements forward.

 
   public static boolean elementsEqual(
       Iterator<?> iterator1Iterator<?> iterator2) {
     while (iterator1.hasNext()) {
       if (!iterator2.hasNext()) {
         return false;
       }
       Object o1 = iterator1.next();
       Object o2 = iterator2.next();
       if (!Objects.equal(o1o2)) {
         return false;
       }
     }
     return !iterator2.hasNext();
   }

  
Returns a string representation of iterator, with the format [e1, e2, ..., en]. The iterator will be left exhausted: its hasNext() method will return false.
 
   public static String toString(Iterator<?> iterator) {
         .appendTo(new StringBuilder().append('['), iterator)
         .append(']')
         .toString();
   }

  
Returns the single element contained in iterator.

Throws:
java.util.NoSuchElementException if the iterator is empty
java.lang.IllegalArgumentException if the iterator contains multiple elements. The state of the iterator is unspecified.
 
   public static <T> T getOnlyElement(Iterator<T> iterator) {
     T first = iterator.next();
     if (!iterator.hasNext()) {
       return first;
     }
 
     StringBuilder sb = new StringBuilder();
     sb.append("expected one element but was: <" + first);
     for (int i = 0; i < 4 && iterator.hasNext(); i++) {
       sb.append(", " + iterator.next());
     }
     if (iterator.hasNext()) {
       sb.append(", ...");
     }
     sb.append('>');
 
     throw new IllegalArgumentException(sb.toString());
   }

  
Returns the single element contained in iterator, or defaultValue if the iterator is empty.

Throws:
java.lang.IllegalArgumentException if the iterator contains multiple elements. The state of the iterator is unspecified.
 
   public static <T> T getOnlyElement(Iterator<? extends T> iterator, @Nullable T defaultValue) {
     return iterator.hasNext() ? getOnlyElement(iterator) : defaultValue;
   }

  
Adds all elements in iterator to collection. The iterator will be left exhausted: its hasNext() method will return false.

Returns:
true if collection was modified as a result of this operation
 
   public static <T> boolean addAll(
       Collection<T> addToIterator<? extends T> iterator) {
     checkNotNull(addTo);
     checkNotNull(iterator);
     boolean wasModified = false;
     while (iterator.hasNext()) {
       wasModified |= addTo.add(iterator.next());
     }
     return wasModified;
   }

  
Returns the number of elements in the specified iterator that equal the specified object. The iterator will be left exhausted: its hasNext() method will return false.

 
   public static int frequency(Iterator<?> iterator, @Nullable Object element) {
     return size(filter(iteratorequalTo(element)));
   }

  
Returns an iterator that cycles indefinitely over the elements of iterable.

The returned iterator supports remove() if the provided iterator does. After remove() is called, subsequent cycles omit the removed element, which is no longer in iterable. The iterator's hasNext() method returns true until iterable is empty.

Warning: Typical uses of the resulting iterator may produce an infinite loop. You should use an explicit break or be certain that you will eventually remove all the elements.

 
   public static <T> Iterator<T> cycle(final Iterable<T> iterable) {
     checkNotNull(iterable);
     return new Iterator<T>() {
       Iterator<T> iterator = emptyIterator();
       Iterator<T> removeFrom;
 
       @Override
       public boolean hasNext() {
         if (!.hasNext()) {
            = iterable.iterator();
         }
         return .hasNext();
       }
       @Override
       public T next() {
         if (!hasNext()) {
           throw new NoSuchElementException();
         }
          = ;
         return .next();
       }
       @Override
       public void remove() {
         checkRemove( != null);
         .remove();
          = null;
       }
     };
   }

  
Returns an iterator that cycles indefinitely over the provided elements.

The returned iterator supports remove(). After remove() is called, subsequent cycles omit the removed element, but elements does not change. The iterator's hasNext() method returns true until all of the original elements have been removed.

Warning: Typical uses of the resulting iterator may produce an infinite loop. You should use an explicit break or be certain that you will eventually remove all the elements.

 
   public static <T> Iterator<T> cycle(T... elements) {
     return cycle(Lists.newArrayList(elements));
   }

  
Combines two iterators into a single iterator. The returned iterator iterates across the elements in a, followed by the elements in b. The source iterators are not polled until necessary.

The returned iterator supports remove() when the corresponding input iterator supports it.

Note: the current implementation is not suitable for nested concatenated iterators, i.e. the following should be avoided when in a loop: iterator = Iterators.concat(iterator, suffix);, since iteration over the resulting iterator has a cubic complexity to the depth of the nesting.

 
   public static <T> Iterator<T> concat(Iterator<? extends T> a,
       Iterator<? extends T> b) {
     return concat(ImmutableList.of(ab).iterator());
   }

  
Combines three iterators into a single iterator. The returned iterator iterates across the elements in a, followed by the elements in b, followed by the elements in c. The source iterators are not polled until necessary.

The returned iterator supports remove() when the corresponding input iterator supports it.

Note: the current implementation is not suitable for nested concatenated iterators, i.e. the following should be avoided when in a loop: iterator = Iterators.concat(iterator, suffix);, since iteration over the resulting iterator has a cubic complexity to the depth of the nesting.

 
   public static <T> Iterator<T> concat(Iterator<? extends T> a,
       Iterator<? extends T> bIterator<? extends T> c) {
     return concat(ImmutableList.of(abc).iterator());
   }

  
Combines four iterators into a single iterator. The returned iterator iterates across the elements in a, followed by the elements in b, followed by the elements in c, followed by the elements in d. The source iterators are not polled until necessary.

The returned iterator supports remove() when the corresponding input iterator supports it.

Note: the current implementation is not suitable for nested concatenated iterators, i.e. the following should be avoided when in a loop: iterator = Iterators.concat(iterator, suffix);, since iteration over the resulting iterator has a cubic complexity to the depth of the nesting.

 
   public static <T> Iterator<T> concat(Iterator<? extends T> a,
       Iterator<? extends T> bIterator<? extends T> c,
       Iterator<? extends T> d) {
     return concat(ImmutableList.of(abcd).iterator());
   }

  
Combines multiple iterators into a single iterator. The returned iterator iterates across the elements of each iterator in inputs. The input iterators are not polled until necessary.

The returned iterator supports remove() when the corresponding input iterator supports it.

Note: the current implementation is not suitable for nested concatenated iterators, i.e. the following should be avoided when in a loop: iterator = Iterators.concat(iterator, suffix);, since iteration over the resulting iterator has a cubic complexity to the depth of the nesting.

Throws:
java.lang.NullPointerException if any of the provided iterators is null
 
   public static <T> Iterator<T> concat(Iterator<? extends T>... inputs) {
     return concat(ImmutableList.copyOf(inputs).iterator());
   }

  
Combines multiple iterators into a single iterator. The returned iterator iterates across the elements of each iterator in inputs. The input iterators are not polled until necessary.

The returned iterator supports remove() when the corresponding input iterator supports it. The methods of the returned iterator may throw NullPointerException if any of the input iterators is null.

Note: the current implementation is not suitable for nested concatenated iterators, i.e. the following should be avoided when in a loop: iterator = Iterators.concat(iterator, suffix);, since iteration over the resulting iterator has a cubic complexity to the depth of the nesting.

 
   public static <T> Iterator<T> concat(
       final Iterator<? extends Iterator<? extends T>> inputs) {
     checkNotNull(inputs);
     return new Iterator<T>() {
       Iterator<? extends T> current = emptyIterator();
       Iterator<? extends T> removeFrom;
 
       @Override
       public boolean hasNext() {
         // http://code.google.com/p/google-collections/issues/detail?id=151
         // current.hasNext() might be relatively expensive, worth minimizing.
         boolean currentHasNext;
         // checkNotNull eager for GWT
         // note: it must be here & not where 'current' is assigned,
         // because otherwise we'll have called inputs.next() before throwing
         // the first NPE, and the next time around we'll call inputs.next()
         // again, incorrectly moving beyond the error.
         while (!(currentHasNext = checkNotNull().hasNext())
             && inputs.hasNext()) {
            = inputs.next();
         }
         return currentHasNext;
       }
       @Override
       public T next() {
         if (!hasNext()) {
           throw new NoSuchElementException();
         }
          = ;
         return .next();
       }
       @Override
       public void remove() {
         checkRemove( != null);
         .remove();
          = null;
       }
     };
   }

  
Divides an iterator into unmodifiable sublists of the given size (the final list may be smaller). For example, partitioning an iterator containing [a, b, c, d, e] with a partition size of 3 yields [[a, b, c], [d, e]] -- an outer iterator containing two inner lists of three and two elements, all in the original order.

The returned lists implement java.util.RandomAccess.

Parameters:
iterator the iterator to return a partitioned view of
size the desired size of each partition (the last may be smaller)
Returns:
an iterator of immutable lists containing the elements of iterator divided into partitions
Throws:
java.lang.IllegalArgumentException if size is nonpositive
 
   public static <T> UnmodifiableIterator<List<T>> partition(
       Iterator<T> iteratorint size) {
     return partitionImpl(iteratorsizefalse);
   }

  
Divides an iterator into unmodifiable sublists of the given size, padding the final iterator with null values if necessary. For example, partitioning an iterator containing [a, b, c, d, e] with a partition size of 3 yields [[a, b, c], [d, e, null]] -- an outer iterator containing two inner lists of three elements each, all in the original order.

The returned lists implement java.util.RandomAccess.

Parameters:
iterator the iterator to return a partitioned view of
size the desired size of each partition
Returns:
an iterator of immutable lists containing the elements of iterator divided into partitions (the final iterable may have trailing null elements)
Throws:
java.lang.IllegalArgumentException if size is nonpositive
 
   public static <T> UnmodifiableIterator<List<T>> paddedPartition(
       Iterator<T> iteratorint size) {
     return partitionImpl(iteratorsizetrue);
   }
 
   private static <T> UnmodifiableIterator<List<T>> partitionImpl(
       final Iterator<T> iteratorfinal int sizefinal boolean pad) {
     checkNotNull(iterator);
     checkArgument(size > 0);
     return new UnmodifiableIterator<List<T>>() {
       @Override
       public boolean hasNext() {
         return iterator.hasNext();
       }
       @Override
       public List<T> next() {
         if (!hasNext()) {
           throw new NoSuchElementException();
         }
         Object[] array = new Object[size];
         int count = 0;
         for (; count < size && iterator.hasNext(); count++) {
           array[count] = iterator.next();
         }
         for (int i = counti < sizei++) {
           array[i] = null// for GWT
         }
 
         @SuppressWarnings("unchecked"// we only put Ts in it
         List<T> list = Collections.unmodifiableList(
             (List<T>) Arrays.asList(array));
         return (pad || count == size) ? list : list.subList(0, count);
       }
     };
   }

  
Returns the elements of unfiltered that satisfy a predicate.
 
   public static <T> UnmodifiableIterator<T> filter(
       final Iterator<T> unfilteredfinal Predicate<? super T> predicate) {
     checkNotNull(unfiltered);
     checkNotNull(predicate);
     return new AbstractIterator<T>() {
       @Override protected T computeNext() {
         while (unfiltered.hasNext()) {
           T element = unfiltered.next();
           if (predicate.apply(element)) {
             return element;
           }
         }
         return endOfData();
       }
     };
   }

  
Returns true if one or more elements returned by iterator satisfy the given predicate.
 
   public static <T> boolean any(
       Iterator<T> iteratorPredicate<? super T> predicate) {
     return indexOf(iteratorpredicate) != -1;
   }

  
Returns true if every element returned by iterator satisfies the given predicate. If iterator is empty, true is returned.
 
   public static <T> boolean all(
       Iterator<T> iteratorPredicate<? super T> predicate) {
     checkNotNull(predicate);
     while (iterator.hasNext()) {
       T element = iterator.next();
       if (!predicate.apply(element)) {
         return false;
       }
     }
     return true;
   }

  
Returns the first element in iterator that satisfies the given predicate; use this method only when such an element is known to exist. If no such element is found, the iterator will be left exhausted: its hasNext() method will return false. If it is possible that no element will match, use tryFind(java.util.Iterator,com.google.common.base.Predicate) or find(java.util.Iterator,com.google.common.base.Predicate,java.lang.Object) instead.

Throws:
java.util.NoSuchElementException if no element in iterator matches the given predicate
 
   public static <T> T find(
       Iterator<T> iteratorPredicate<? super T> predicate) {
     return filter(iteratorpredicate).next();
   }

  
Returns the first element in iterator that satisfies the given predicate. If no such element is found, defaultValue will be returned from this method and the iterator will be left exhausted: its hasNext() method will return false. Note that this can usually be handled more naturally using tryFind(iterator, predicate).or(defaultValue).

Since:
7.0
 
   public static <T> T find(Iterator<? extends T> iteratorPredicate<? super T> predicate,
       @Nullable T defaultValue) {
     return getNext(filter(iteratorpredicate), defaultValue);
   }

  
Returns an com.google.common.base.Optional containing the first element in iterator that satisfies the given predicate, if such an element exists. If no such element is found, an empty com.google.common.base.Optional will be returned from this method and the iterator will be left exhausted: its hasNext() method will return false.

Warning: avoid using a predicate that matches null. If null is matched in iterator, a NullPointerException will be thrown.

Since:
11.0
 
   public static <T> Optional<T> tryFind(
       Iterator<T> iteratorPredicate<? super T> predicate) {
     UnmodifiableIterator<T> filteredIterator = filter(iteratorpredicate);
     return filteredIterator.hasNext()
         ? Optional.of(filteredIterator.next())
         : Optional.<T>absent();
   }

  
Returns the index in iterator of the first element that satisfies the provided predicate, or -1 if the Iterator has no such elements.

More formally, returns the lowest index i such that predicate.apply(Iterators.get(iterator, i)) returns true, or -1 if there is no such index.

If -1 is returned, the iterator will be left exhausted: its hasNext() method will return false. Otherwise, the iterator will be set to the element which satisfies the predicate.

Since:
2.0
 
   public static <T> int indexOf(
       Iterator<T> iteratorPredicate<? super T> predicate) {
     checkNotNull(predicate"predicate");
     for (int i = 0; iterator.hasNext(); i++) {
       T current = iterator.next();
       if (predicate.apply(current)) {
         return i;
       }
     }
     return -1;
   }

  
Returns an iterator that applies function to each element of fromIterator.

The returned iterator supports remove() if the provided iterator does. After a successful remove() call, fromIterator no longer contains the corresponding element.

 
   public static <F, T> Iterator<T> transform(final Iterator<F> fromIterator,
       final Function<? super F, ? extends T> function) {
     checkNotNull(function);
     return new TransformedIterator<F, T>(fromIterator) {
       @Override
       T transform(F from) {
         return function.apply(from);
       }
     };
   }

  
Advances iterator position + 1 times, returning the element at the positionth position.

Parameters:
position position of the element to return
Returns:
the element at the specified position in iterator
Throws:
java.lang.IndexOutOfBoundsException if position is negative or greater than or equal to the number of elements remaining in iterator
 
   public static <T> T get(Iterator<T> iteratorint position) {
     checkNonnegative(position);
     int skipped = advance(iteratorposition);
     if (!iterator.hasNext()) {
       throw new IndexOutOfBoundsException("position (" + position
           + ") must be less than the number of elements that remained ("
           + skipped + ")");
     }
     return iterator.next();
   }
 
   static void checkNonnegative(int position) {
     if (position < 0) {
       throw new IndexOutOfBoundsException("position (" + position
           + ") must not be negative");
     }
   }

  
Advances iterator position + 1 times, returning the element at the positionth position or defaultValue otherwise.

Parameters:
position position of the element to return
defaultValue the default value to return if the iterator is empty or if position is greater than the number of elements remaining in iterator
Returns:
the element at the specified position in iterator or defaultValue if iterator produces fewer than position + 1 elements.
Throws:
java.lang.IndexOutOfBoundsException if position is negative
Since:
4.0
 
   public static <T> T get(Iterator<? extends T> iteratorint position, @Nullable T defaultValue) {
     checkNonnegative(position);
     advance(iteratorposition);
     return getNext(iteratordefaultValue);
   }

  
Returns the next element in iterator or defaultValue if the iterator is empty. The Iterables analog to this method is Iterables.getFirst(java.lang.Iterable,java.lang.Object).

Parameters:
defaultValue the default value to return if the iterator is empty
Returns:
the next element of iterator or the default value
Since:
7.0
 
   public static <T> T getNext(Iterator<? extends T> iterator, @Nullable T defaultValue) {
     return iterator.hasNext() ? iterator.next() : defaultValue;
   }

  
Advances iterator to the end, returning the last element.

Returns:
the last element of iterator
Throws:
java.util.NoSuchElementException if the iterator is empty
 
   public static <T> T getLast(Iterator<T> iterator) {
     while (true) {
       T current = iterator.next();
       if (!iterator.hasNext()) {
         return current;
       }
     }
   }

  
Advances iterator to the end, returning the last element or defaultValue if the iterator is empty.

Parameters:
defaultValue the default value to return if the iterator is empty
Returns:
the last element of iterator
Since:
3.0
 
   public static <T> T getLast(Iterator<? extends T> iterator, @Nullable T defaultValue) {
     return iterator.hasNext() ? getLast(iterator) : defaultValue;
   }

  
Calls next() on iterator, either numberToAdvance times or until hasNext() returns false, whichever comes first.

Returns:
the number of elements the iterator was advanced
Since:
13.0 (since 3.0 as Iterators.skip)
 
   public static int advance(Iterator<?> iteratorint numberToAdvance) {
     checkNotNull(iterator);
     checkArgument(numberToAdvance >= 0, "numberToAdvance must be nonnegative");
 
     int i;
     for (i = 0; i < numberToAdvance && iterator.hasNext(); i++) {
       iterator.next();
     }
     return i;
   }

  
Creates an iterator returning the first limitSize elements of the given iterator. If the original iterator does not contain that many elements, the returned iterator will have the same behavior as the original iterator. The returned iterator supports remove() if the original iterator does.

Parameters:
iterator the iterator to limit
limitSize the maximum number of elements in the returned iterator
Throws:
java.lang.IllegalArgumentException if limitSize is negative
Since:
3.0
 
   public static <T> Iterator<T> limit(
       final Iterator<T> iteratorfinal int limitSize) {
     checkNotNull(iterator);
     checkArgument(limitSize >= 0, "limit is negative");
     return new Iterator<T>() {
       private int count;
 
       @Override
       public boolean hasNext() {
         return  < limitSize && iterator.hasNext();
       }
 
       @Override
       public T next() {
         if (!hasNext()) {
           throw new NoSuchElementException();
         }
         ++;
         return iterator.next();
       }
 
       @Override
       public void remove() {
         iterator.remove();
       }
     };
   }

  
Returns a view of the supplied iterator that removes each element from the supplied iterator as it is returned.

The provided iterator must support java.util.Iterator.remove() or else the returned iterator will fail on the first call to next.

Parameters:
iterator the iterator to remove and return elements from
Returns:
an iterator that removes and returns elements from the supplied iterator
Since:
2.0
 
   public static <T> Iterator<T> consumingIterator(final Iterator<T> iterator) {
     checkNotNull(iterator);
     return new UnmodifiableIterator<T>() {
       @Override
       public boolean hasNext() {
         return iterator.hasNext();
       }
 
       @Override
       public T next() {
         T next = iterator.next();
         iterator.remove();
         return next;
       }
 
       @Override
       public String toString() {
         return "Iterators.consumingIterator(...)";
       }
     };
   }

  
Deletes and returns the next value from the iterator, or returns null if there is no such value.
 
   static <T> T pollNext(Iterator<T> iterator) {
     if (iterator.hasNext()) {
       T result = iterator.next();
       iterator.remove();
       return result;
     } else {
       return null;
     }
   }
 
   // Methods only in Iterators, not in Iterables
 
  
Clears the iterator using its remove method.
 
   static void clear(Iterator<?> iterator) {
     checkNotNull(iterator);
     while (iterator.hasNext()) {
       iterator.next();
       iterator.remove();
     }
   }

  
Returns an iterator containing the elements of array in order. The returned iterator is a view of the array; subsequent changes to the array will be reflected in the iterator.

Note: It is often preferable to represent your data using a collection type, for example using java.util.Arrays.asList(java.lang.Object[]), making this method unnecessary.

The Iterable equivalent of this method is either java.util.Arrays.asList(java.lang.Object[]), ImmutableList.copyOf(java.lang.Object[])}, or ImmutableList.of().

 
   public static <T> UnmodifiableIterator<T> forArray(final T... array) {
     return forArray(array, 0, array.length, 0);
   }

  
Returns a list iterator containing the elements in the specified range of array in order, starting at the specified index.

The Iterable equivalent of this method is Arrays.asList(array).subList(offset, offset + length).listIterator(index).

      final T[] arrayfinal int offsetint lengthint index) {
    checkArgument(length >= 0);
    int end = offset + length;
    // Technically we should give a slightly more descriptive error on overflow
    Preconditions.checkPositionIndexes(offsetendarray.length);
    Preconditions.checkPositionIndex(indexlength);
    if (length == 0) {
      return emptyListIterator();
    }
    /*
     * We can't use call the two-arg constructor with arguments (offset, end)
     * because the returned Iterator is a ListIterator that may be moved back
     * past the beginning of the iteration.
     */
    return new AbstractIndexedListIterator<T>(lengthindex) {
      @Override protected T get(int index) {
        return array[offset + index];
      }
    };
  }

  
Returns an iterator containing only value.

The java.lang.Iterable equivalent of this method is java.util.Collections.singleton(java.lang.Object).

  public static <T> UnmodifiableIterator<T> singletonIterator(
      @Nullable final T value) {
    return new UnmodifiableIterator<T>() {
      boolean done;
      @Override
      public boolean hasNext() {
        return !;
      }
      @Override
      public T next() {
        if () {
          throw new NoSuchElementException();
        }
         = true;
        return value;
      }
    };
  }

  
Adapts an Enumeration to the Iterator interface.

This method has no equivalent in Iterables because viewing an Enumeration as an Iterable is impossible. However, the contents can be copied into a collection using java.util.Collections.list(java.util.Enumeration).

  public static <T> UnmodifiableIterator<T> forEnumeration(
      final Enumeration<T> enumeration) {
    checkNotNull(enumeration);
    return new UnmodifiableIterator<T>() {
      @Override
      public boolean hasNext() {
        return enumeration.hasMoreElements();
      }
      @Override
      public T next() {
        return enumeration.nextElement();
      }
    };
  }

  
Adapts an Iterator to the Enumeration interface.

The Iterable equivalent of this method is either java.util.Collections.enumeration(java.util.Collection) (if you have a java.util.Collection), or Iterators.asEnumeration(collection.iterator()).

  public static <T> Enumeration<T> asEnumeration(final Iterator<T> iterator) {
    checkNotNull(iterator);
    return new Enumeration<T>() {
      @Override
      public boolean hasMoreElements() {
        return iterator.hasNext();
      }
      @Override
      public T nextElement() {
        return iterator.next();
      }
    };
  }

  
Implementation of PeekingIterator that avoids peeking unless necessary.
  private static class PeekingImpl<E> implements PeekingIterator<E> {
    private final Iterator<? extends E> iterator;
    private boolean hasPeeked;
    private E peekedElement;
    public PeekingImpl(Iterator<? extends E> iterator) {
      this. = checkNotNull(iterator);
    }
    @Override
    public boolean hasNext() {
      return  || .hasNext();
    }
    @Override
    public E next() {
      if (!) {
        return .next();
      }
      E result = ;
       = false;
       = null;
      return result;
    }
    @Override
    public void remove() {
      checkState(!"Can't remove after you've peeked at next");
      .remove();
    }
    @Override
    public E peek() {
      if (!) {
         = .next();
         = true;
      }
      return ;
    }
  }

  
Returns a PeekingIterator backed by the given iterator.

Calls to the peek method with no intervening calls to next do not affect the iteration, and hence return the same object each time. A subsequent call to next is guaranteed to return the same object again. For example:

   PeekingIterator<String> peekingIterator =
       Iterators.peekingIterator(Iterators.forArray("a", "b"));
   String a1 = peekingIterator.peek(); // returns "a"
   String a2 = peekingIterator.peek(); // also returns "a"
   String a3 = peekingIterator.next(); // also returns "a"

Any structural changes to the underlying iteration (aside from those performed by the iterator's own com.google.common.collect.PeekingIterator.remove() method) will leave the iterator in an undefined state.

The returned iterator does not support removal after peeking, as explained by com.google.common.collect.PeekingIterator.remove().

Note: If the given iterator is already a PeekingIterator, it might be returned to the caller, although this is neither guaranteed to occur nor required to be consistent. For example, this method might choose to pass through recognized implementations of PeekingIterator when the behavior of the implementation is known to meet the contract guaranteed by this method.

There is no java.lang.Iterable equivalent to this method, so use this method to wrap each individual iterator as it is generated.

Parameters:
iterator the backing iterator. The com.google.common.collect.PeekingIterator assumes ownership of this iterator, so users should cease making direct calls to it after calling this method.
Returns:
a peeking iterator backed by that iterator. Apart from the additional com.google.common.collect.PeekingIterator.peek() method, this iterator behaves exactly the same as iterator.
  public static <T> PeekingIterator<T> peekingIterator(
      Iterator<? extends T> iterator) {
    if (iterator instanceof PeekingImpl) {
      // Safe to cast <? extends T> to <T> because PeekingImpl only uses T
      // covariantly (and cannot be subclassed to add non-covariant uses).
      @SuppressWarnings("unchecked")
      PeekingImpl<T> peeking = (PeekingImpl<T>) iterator;
      return peeking;
    }
    return new PeekingImpl<T>(iterator);
  }

  
Simply returns its argument.

Deprecated:
no need to use this
Since:
10.0
  @Deprecated public static <T> PeekingIterator<T> peekingIterator(
      PeekingIterator<T> iterator) {
    return checkNotNull(iterator);
  }

  
Returns an iterator over the merged contents of all given iterators, traversing every element of the input iterators. Equivalent entries will not be de-duplicated.

Callers must ensure that the source iterators are in non-descending order as this method does not sort its input.

For any equivalent elements across all iterators, it is undefined which element is returned first.

Since:
11.0
  public static <T> UnmodifiableIterator<T> mergeSorted(
      Iterable<? extends Iterator<? extends T>> iterators,
      Comparator<? super T> comparator) {
    checkNotNull(iterators"iterators");
    checkNotNull(comparator"comparator");
    return new MergingIterator<T>(iteratorscomparator);
  }

  
An iterator that performs a lazy N-way merge, calculating the next value each time the iterator is polled. This amortizes the sorting cost over the iteration and requires less memory than sorting all elements at once.

Retrieving a single element takes approximately O(log(M)) time, where M is the number of iterators. (Retrieving all elements takes approximately O(N*log(M)) time, where N is the total number of elements.)

  private static class MergingIterator<T> extends UnmodifiableIterator<T> {
    final Queue<PeekingIterator<T>> queue;
    public MergingIterator(Iterable<? extends Iterator<? extends T>> iterators,
        final Comparator<? super T> itemComparator) {
      // A comparator that's used by the heap, allowing the heap
      // to be sorted based on the top of each iterator.
      Comparator<PeekingIterator<T>> heapComparator =
          new Comparator<PeekingIterator<T>>() {
            @Override
            public int compare(PeekingIterator<T> o1PeekingIterator<T> o2) {
              return itemComparator.compare(o1.peek(), o2.peek());
            }
          };
       = new PriorityQueue<PeekingIterator<T>>(2, heapComparator);
      for (Iterator<? extends T> iterator : iterators) {
        if (iterator.hasNext()) {
          .add(Iterators.peekingIterator(iterator));
        }
      }
    }
    @Override
    public boolean hasNext() {
      return !.isEmpty();
    }
    @Override
    public T next() {
      PeekingIterator<T> nextIter = .remove();
      T next = nextIter.next();
      if (nextIter.hasNext()) {
        .add(nextIter);
      }
      return next;
    }
  }

  
Used to avoid http://bugs.sun.com/view_bug.do?bug_id=6558557
  static <T> ListIterator<T> cast(Iterator<T> iterator) {
    return (ListIterator<T>) iterator;
  }
New to GrepCode? Check out our FAQ X