@Override
  public final String escape(String s) {
    checkNotNull(s); // GWT specific check (do not optimize)
    for (int i = 0; i < s.length(); i++) {
      char c = s.charAt(i);
      if ((c < replacementsLength && replacements[c] != null)
          || c > safeMaxChar
          || c < safeMinChar) {
        return escapeSlow(s, i);
      }
    }
    return s;
  }

@
Override
public
final
String
escape
(
String
s
)
{
checkNotNull
(
s
)
;
// GWT specific check (do not optimize)
for
(
int
i
=
0
;
i
<
s
.
length
(
)
;
i
++
)
{
char
c
=
s
.
charAt
(
i
)
;
if
(
(
c
<
replacementsLength
&&
replacements
[
c
]
!=
)
||
c
>
safeMaxChar
||
c
<
safeMinChar
)
{
return
escapeSlow
(
s
,
i
)
;
}
}
return
s
;
}

/*
This is overridden to improve performance. Rough benchmarking shows that this almost doubles
the speed when processing strings that do not require any escaping.

/ * This is overridden to improve performance . Rough benchmarking shows that this almost doubles the speed when processing strings that do not require any escaping .


@Override
  protected final char[] escape(int cp) {
    if (cp < replacementsLength) {
      char[] chars = replacements[cp];
      if (chars != null) {
        return chars;
      }
    }
    if (cp >= safeMin && cp <= safeMax) {
      return null;
    }
    return escapeUnsafe(cp);
  }

@ Override protected final char [ ] escape ( int cp ) { if ( cp < replacementsLength ) { char [ ] chars = replacements [ cp ] ; if ( chars != null ) { return chars ; } } if ( cp >= safeMin && cp <= safeMax ) { return null ; } return escapeUnsafe ( cp ) ; }

Escapes a single Unicode code point using the replacement array and safe range values. If the
given character does not have an explicit replacement and lies outside the safe range then
{@link #escapeUnsafe} is called.

Escapes a single Unicode code point using the replacement array and safe range values . If the given character does not have an explicit replacement and lies outside the safe range then {


@Override
  protected final int nextEscapeIndex(CharSequence csq, int index, int end) {
    while (index < end) {
      char c = csq.charAt(index);
      if ((c < replacementsLength && replacements[c] != null)
          || c > safeMaxChar
          || c < safeMinChar) {
        break;
      }
      index++;
    }
    return index;
  }

@ Override protected final int nextEscapeIndex ( CharSequence csq , int index , int end ) { while ( index < end ) { char c = csq . charAt ( index ) ; if ( ( c < replacementsLength && replacements [ c ] != null ) || c > safeMaxChar || c < safeMinChar ) { break ; } index ++ ; } return index ; }


public BufferedReader openBufferedStream() throws IOException {
    Reader reader = openStream();
    return (reader instanceof BufferedReader)
        ? (BufferedReader) reader
        : new BufferedReader(reader);
  }

public BufferedReader openBufferedStream ( ) throws IOException { Reader reader = openStream ( ) ; return ( reader instanceof BufferedReader ) ? ( BufferedReader ) reader : new BufferedReader ( reader ) ; }

Opens a new {@link BufferedReader} for reading from this source. This method returns a new,
independent reader each time it is called.

<p>The caller is responsible for ensuring that the returned reader is closed.

@throws IOException if an I/O error occurs while of opening the reader

Opens a new { @link BufferedReader } for reading from this source . This method returns a new independent reader each time it is called .


@Beta
  public long length() throws IOException {
    Optional<Long> lengthIfKnown = lengthIfKnown();
    if (lengthIfKnown.isPresent()) {
      return lengthIfKnown.get();
    }

    Closer closer = Closer.create();
    try {
      Reader reader = closer.register(openStream());
      return countBySkipping(reader);
    } catch (Throwable e) {
      throw closer.rethrow(e);
    } finally {
      closer.close();
    }
  }

@ Beta public long length ( ) throws IOException { Optional < Long > lengthIfKnown = lengthIfKnown ( ) ; if ( lengthIfKnown . isPresent ( ) ) { return lengthIfKnown . get ( ) ; } Closer closer = Closer . create ( ) ; try { Reader reader = closer . register ( openStream ( ) ) ; return countBySkipping ( reader ) ; } catch ( Throwable e ) { throw closer . rethrow ( e ) ; } finally { closer . close ( ) ; } }

Returns the length of this source in chars, even if doing so requires opening and traversing an
entire stream. To avoid a potentially expensive operation, see {@link #lengthIfKnown}.

The default implementation calls {@link #lengthIfKnown} and returns the value if present. If
absent, it will fall back to a heavyweight operation that will open a stream, {@link
Reader#skip(long) skip} to the end of the stream, and return the total number of chars that
were skipped.

Note that for sources that implement {@link #lengthIfKnown} to provide a more efficient
implementation, it is possible that this method will return a different number of chars
than would be returned by reading all of the chars.

In either case, for mutable sources such as files, a subsequent read may return a different
number of chars if the contents are changed.

@throws IOException if an I/O error occurs while reading the length of this source
@since 19.0

Returns the length of this source in chars even if doing so requires opening and traversing an entire stream . To avoid a potentially expensive operation see { @link #lengthIfKnown } .


@CanIgnoreReturnValue
  public long copyTo(CharSink sink) throws IOException {
    checkNotNull(sink);

    Closer closer = Closer.create();
    try {
      Reader reader = closer.register(openStream());
      Writer writer = closer.register(sink.openStream());
      return CharStreams.copy(reader, writer);
    } catch (Throwable e) {
      throw closer.rethrow(e);
    } finally {
      closer.close();
    }
  }

@ CanIgnoreReturnValue public long copyTo ( CharSink sink ) throws IOException { checkNotNull ( sink ) ; Closer closer = Closer . create ( ) ; try { Reader reader = closer . register ( openStream ( ) ) ; Writer writer = closer . register ( sink . openStream ( ) ) ; return CharStreams . copy ( reader , writer ) ; } catch ( Throwable e ) { throw closer . rethrow ( e ) ; } finally { closer . close ( ) ; } }

Copies the contents of this source to the given sink.

@return the number of characters copied
@throws IOException if an I/O error occurs while reading from this source or writing to {@code
sink}

Copies the contents of this source to the given sink .


public String read() throws IOException {
    Closer closer = Closer.create();
    try {
      Reader reader = closer.register(openStream());
      return CharStreams.toString(reader);
    } catch (Throwable e) {
      throw closer.rethrow(e);
    } finally {
      closer.close();
    }
  }

public String read ( ) throws IOException { Closer closer = Closer . create ( ) ; try { Reader reader = closer . register ( openStream ( ) ) ; return CharStreams . toString ( reader ) ; } catch ( Throwable e ) { throw closer . rethrow ( e ) ; } finally { closer . close ( ) ; } }

Reads the contents of this source as a string.

@throws IOException if an I/O error occurs while reading from this source

Reads the contents of this source as a string .


@NullableDecl
  public String readFirstLine() throws IOException {
    Closer closer = Closer.create();
    try {
      BufferedReader reader = closer.register(openBufferedStream());
      return reader.readLine();
    } catch (Throwable e) {
      throw closer.rethrow(e);
    } finally {
      closer.close();
    }
  }

@ NullableDecl public String readFirstLine ( ) throws IOException { Closer closer = Closer . create ( ) ; try { BufferedReader reader = closer . register ( openBufferedStream ( ) ) ; return reader . readLine ( ) ; } catch ( Throwable e ) { throw closer . rethrow ( e ) ; } finally { closer . close ( ) ; } }

Reads the first line of this source as a string. Returns {@code null} if this source is empty.

<p>Like {@link BufferedReader#readLine()}, this method considers a line to be a sequence of
text that is terminated by (but does not include) one of {@code \r\n}, {@code \r} or {@code
\n}. If the source's content does not end in a line termination sequence, it is treated as if
it does.

@throws IOException if an I/O error occurs while reading from this source

Reads the first line of this source as a string . Returns { @code null } if this source is empty .


public ImmutableList<String> readLines() throws IOException {
    Closer closer = Closer.create();
    try {
      BufferedReader reader = closer.register(openBufferedStream());
      List<String> result = Lists.newArrayList();
      String line;
      while ((line = reader.readLine()) != null) {
        result.add(line);
      }
      return ImmutableList.copyOf(result);
    } catch (Throwable e) {
      throw closer.rethrow(e);
    } finally {
      closer.close();
    }
  }

public ImmutableList < String > readLines ( ) throws IOException { Closer closer = Closer . create ( ) ; try { BufferedReader reader = closer . register ( openBufferedStream ( ) ) ; List < String > result = Lists . newArrayList ( ) ; String line ; while ( ( line = reader . readLine ( ) ) != null ) { result . add ( line ) ; } return ImmutableList . copyOf ( result ) ; } catch ( Throwable e ) { throw closer . rethrow ( e ) ; } finally { closer . close ( ) ; } }

Reads all the lines of this source as a list of strings. The returned list will be empty if
this source is empty.

<p>Like {@link BufferedReader#readLine()}, this method considers a line to be a sequence of
text that is terminated by (but does not include) one of {@code \r\n}, {@code \r} or {@code
\n}. If the source's content does not end in a line termination sequence, it is treated as if
it does.

@throws IOException if an I/O error occurs while reading from this source

Reads all the lines of this source as a list of strings . The returned list will be empty if this source is empty .


public boolean isEmpty() throws IOException {
    Optional<Long> lengthIfKnown = lengthIfKnown();
    if (lengthIfKnown.isPresent()) {
      return lengthIfKnown.get() == 0L;
    }
    Closer closer = Closer.create();
    try {
      Reader reader = closer.register(openStream());
      return reader.read() == -1;
    } catch (Throwable e) {
      throw closer.rethrow(e);
    } finally {
      closer.close();
    }
  }

public boolean isEmpty ( ) throws IOException { Optional < Long > lengthIfKnown = lengthIfKnown ( ) ; if ( lengthIfKnown . isPresent ( ) ) { return lengthIfKnown . get ( ) == 0L ; } Closer closer = Closer . create ( ) ; try { Reader reader = closer . register ( openStream ( ) ) ; return reader . read ( ) == - 1 ; } catch ( Throwable e ) { throw closer . rethrow ( e ) ; } finally { closer . close ( ) ; } }

Returns whether the source has zero chars. The default implementation first checks {@link
#lengthIfKnown}, returning true if it's known to be zero and false if it's known to be
non-zero. If the length is not known, it falls back to opening a stream and checking for EOF.

Note that, in cases where {@code lengthIfKnown} returns zero, it is possible that
chars are actually available for reading. This means that a source may return {@code true} from
{@code isEmpty()} despite having readable content.

@throws IOException if an I/O error occurs
@since 15.0

Returns whether the source has zero chars . The default implementation first checks { @link #lengthIfKnown } returning true if it s known to be zero and false if it s known to be non - zero . If the length is not known it falls back to opening a stream and checking for EOF .


public static CharSource wrap(CharSequence charSequence) {
    return charSequence instanceof String
        ? new StringCharSource((String) charSequence)
        : new CharSequenceCharSource(charSequence);
  }

public static CharSource wrap ( CharSequence charSequence ) { return charSequence instanceof String ? new StringCharSource ( ( String ) charSequence ) : new CharSequenceCharSource ( charSequence ) ; }

Returns a view of the given character sequence as a {@link CharSource}. The behavior of the
returned {@code CharSource} and any {@code Reader} instances created by it is unspecified if
the {@code charSequence} is mutated while it is being read, so don't do that.

@since 15.0 (since 14.0 as {@code CharStreams.asCharSource(String)})

Returns a view of the given character sequence as a { @link CharSource } . The behavior of the returned { @code CharSource } and any { @code Reader } instances created by it is unspecified if the { @code charSequence } is mutated while it is being read so don t do that .


@Override
  public int read(byte[] b, int off, int len) throws IOException {
    // Obey InputStream contract.
    checkPositionIndexes(off, off + len, b.length);
    if (len == 0) {
      return 0;
    }

    // The rest of this method implements the process described by the CharsetEncoder javadoc.
    int totalBytesRead = 0;
    boolean doneEncoding = endOfInput;

    DRAINING:
    while (true) {
      // We stay in draining mode until there are no bytes left in the output buffer. Then we go
      // back to encoding/flushing.
      if (draining) {
        totalBytesRead += drain(b, off + totalBytesRead, len - totalBytesRead);
        if (totalBytesRead == len || doneFlushing) {
          return (totalBytesRead > 0) ? totalBytesRead : -1;
        }
        draining = false;
        byteBuffer.clear();
      }

      while (true) {
        // We call encode until there is no more input. The last call to encode will have endOfInput
        // == true. Then there is a final call to flush.
        CoderResult result;
        if (doneFlushing) {
          result = CoderResult.UNDERFLOW;
        } else if (doneEncoding) {
          result = encoder.flush(byteBuffer);
        } else {
          result = encoder.encode(charBuffer, byteBuffer, endOfInput);
        }

        if (result.isOverflow()) {
          // Not enough room in output buffer--drain it, creating a bigger buffer if necessary.
          startDraining(true);
          continue DRAINING;
        } else if (result.isUnderflow()) {
          // If encoder underflows, it means either:
          // a) the final flush() succeeded; next drain (then done)
          // b) we encoded all of the input; next flush
          // c) we ran of out input to encode; next read more input
          if (doneEncoding) { // (a)
            doneFlushing = true;
            startDraining(false);
            continue DRAINING;
          } else if (endOfInput) { // (b)
            doneEncoding = true;
          } else { // (c)
            readMoreChars();
          }
        } else if (result.isError()) {
          // Only reach here if a CharsetEncoder with non-REPLACE settings is used.
          result.throwException();
          return 0; // Not called.
        }
      }
    }
  }


private static CharBuffer grow(CharBuffer buf) {
    char[] copy = Arrays.copyOf(buf.array(), buf.capacity() * 2);
    CharBuffer bigger = CharBuffer.wrap(copy);
    bigger.position(buf.position());
    bigger.limit(buf.limit());
    return bigger;
  }

private static CharBuffer grow ( CharBuffer buf ) { char [ ] copy = Arrays . copyOf ( buf . array ( ) , buf . capacity ( ) * 2 ) ; CharBuffer bigger = CharBuffer . wrap ( copy ) ; bigger . position ( buf . position ( ) ) ; bigger . limit ( buf . limit ( ) ) ; return bigger ; }

Returns a new CharBuffer identical to buf, except twice the capacity.

Returns a new CharBuffer identical to buf except twice the capacity .


private void readMoreChars() throws IOException {
    // Possibilities:
    // 1) array has space available on right hand side (between limit and capacity)
    // 2) array has space available on left hand side (before position)
    // 3) array has no space available
    //
    // In case 2 we shift the existing chars to the left, and in case 3 we create a bigger
    // array, then they both become case 1.

    if (availableCapacity(charBuffer) == 0) {
      if (charBuffer.position() > 0) {
        // (2) There is room in the buffer. Move existing bytes to the beginning.
        charBuffer.compact().flip();
      } else {
        // (3) Entire buffer is full, need bigger buffer.
        charBuffer = grow(charBuffer);
      }
    }

    // (1) Read more characters into free space at end of array.
    int limit = charBuffer.limit();
    int numChars = reader.read(charBuffer.array(), limit, availableCapacity(charBuffer));
    if (numChars == -1) {
      endOfInput = true;
    } else {
      charBuffer.limit(limit + numChars);
    }
  }

Handle the case of underflow caused by needing more input characters.

Handle the case of underflow caused by needing more input characters .


private void startDraining(boolean overflow) {
    byteBuffer.flip();
    if (overflow && byteBuffer.remaining() == 0) {
      byteBuffer = ByteBuffer.allocate(byteBuffer.capacity() * 2);
    } else {
      draining = true;
    }
  }

private void startDraining ( boolean overflow ) { byteBuffer . flip ( ) ; if ( overflow && byteBuffer . remaining ( ) == 0 ) { byteBuffer = ByteBuffer . allocate ( byteBuffer . capacity ( ) * 2 ) ; } else { draining = true ; } }

Flips the buffer output buffer so we can start reading bytes from it. If we are starting to
drain because there was overflow, and there aren't actually any characters to drain, then the
overflow must be due to a small output buffer.

Flips the buffer output buffer so we can start reading bytes from it . If we are starting to drain because there was overflow and there aren t actually any characters to drain then the overflow must be due to a small output buffer .


private int drain(byte[] b, int off, int len) {
    int remaining = Math.min(len, byteBuffer.remaining());
    byteBuffer.get(b, off, remaining);
    return remaining;
  }

private int drain ( byte [ ] b , int off , int len ) { int remaining = Math . min ( len , byteBuffer . remaining ( ) ) ; byteBuffer . get ( b , off , remaining ) ; return remaining ; }

Copy as much of the byte buffer into the output array as possible, returning the (positive)
number of characters copied.

Copy as much of the byte buffer into the output array as possible returning the ( positive ) number of characters copied .


protected Entry<K, V> standardLowerEntry(K key) {
    return headMap(key, false).lastEntry();
  }

protected Entry < K , V > standardLowerEntry ( K key ) { return headMap ( key , false ) . lastEntry ( ) ; }

A sensible definition of {@link #lowerEntry} in terms of the {@code lastEntry()} of {@link
#headMap(Object, boolean)}. If you override {@code headMap}, you may wish to override {@code
lowerEntry} to forward to this implementation.


protected Entry<K, V> standardFloorEntry(K key) {
    return headMap(key, true).lastEntry();
  }

protected Entry < K , V > standardFloorEntry ( K key ) { return headMap ( key , true ) . lastEntry ( ) ; }

A sensible definition of {@link #floorEntry} in terms of the {@code lastEntry()} of {@link
#headMap(Object, boolean)}. If you override {@code headMap}, you may wish to override {@code
floorEntry} to forward to this implementation.


protected Entry<K, V> standardCeilingEntry(K key) {
    return tailMap(key, true).firstEntry();
  }

protected Entry < K , V > standardCeilingEntry ( K key ) { return tailMap ( key , true ) . firstEntry ( ) ; }

A sensible definition of {@link #ceilingEntry} in terms of the {@code firstEntry()} of {@link
#tailMap(Object, boolean)}. If you override {@code tailMap}, you may wish to override {@code
ceilingEntry} to forward to this implementation.


protected Entry<K, V> standardHigherEntry(K key) {
    return tailMap(key, false).firstEntry();
  }

protected Entry < K , V > standardHigherEntry ( K key ) { return tailMap ( key , false ) . firstEntry ( ) ; }

A sensible definition of {@link #higherEntry} in terms of the {@code firstEntry()} of {@link
#tailMap(Object, boolean)}. If you override {@code tailMap}, you may wish to override {@code
higherEntry} to forward to this implementation.


protected K standardFirstKey() {
    Entry<K, V> entry = firstEntry();
    if (entry == null) {
      throw new NoSuchElementException();
    } else {
      return entry.getKey();
    }
  }

protected K standardFirstKey ( ) { Entry < K , V > entry = firstEntry ( ) ; if ( entry == null ) { throw new NoSuchElementException ( ) ; } else { return entry . getKey ( ) ; } }

A sensible definition of {@link #firstKey} in terms of {@code firstEntry}. If you override
{@code firstEntry}, you may wish to override {@code firstKey} to forward to this
implementation.


protected K standardLastKey() {
    Entry<K, V> entry = lastEntry();
    if (entry == null) {
      throw new NoSuchElementException();
    } else {
      return entry.getKey();
    }
  }

protected K standardLastKey ( ) { Entry < K , V > entry = lastEntry ( ) ; if ( entry == null ) { throw new NoSuchElementException ( ) ; } else { return entry . getKey ( ) ; } }

A sensible definition of {@link #lastKey} in terms of {@code lastEntry}. If you override {@code
lastEntry}, you may wish to override {@code lastKey} to forward to this implementation.


protected long edgeCount() {
    long degreeSum = 0L;
    for (N node : nodes()) {
      degreeSum += degree(node);
    }
    // According to the degree sum formula, this is equal to twice the number of edges.
    checkState((degreeSum & 1) == 0);
    return degreeSum >>> 1;
  }

Returns the number of edges in this graph; used to calculate the size of {@link #edges()}. This
implementation requires O(|N|) time. Classes extending this one may manually keep track of the
number of edges as the graph is updated, and override this method for better performance.

Returns the number of edges in this graph ; used to calculate the size of {


@Override
  public Set<EndpointPair<N>> edges() {
    return new AbstractSet<EndpointPair<N>>() {
      @Override
      public UnmodifiableIterator<EndpointPair<N>> iterator() {
        return EndpointPairIterator.of(AbstractBaseGraph.this);
      }

      @Override
      public int size() {
        return Ints.saturatedCast(edgeCount());
      }

      @Override
      public boolean remove(Object o) {
        throw new UnsupportedOperationException();
      }

      // Mostly safe: We check contains(u) before calling successors(u), so we perform unsafe
      // operations only in weird cases like checking for an EndpointPair<ArrayList> in a
      // Graph<LinkedList>.
      @SuppressWarnings("unchecked")
      @Override
      public boolean contains(@NullableDecl Object obj) {
        if (!(obj instanceof EndpointPair)) {
          return false;
        }
        EndpointPair<?> endpointPair = (EndpointPair<?>) obj;
        return isOrderingCompatible(endpointPair)
            && nodes().contains(endpointPair.nodeU())
            && successors((N) endpointPair.nodeU()).contains(endpointPair.nodeV());
      }
    };
  }

An implementation of {@link BaseGraph#edges()} defined in terms of {@link #nodes()} and {@link
#successors(Object)}.


@CanIgnoreReturnValue
  int copyIntoArray(Object[] dst, int offset) {
    for (E e : this) {
      dst[offset++] = e;
    }
    return offset;
  }

@ CanIgnoreReturnValue int copyIntoArray ( Object [ ] dst , int offset ) { for ( E e : this ) { dst [ offset ++ ] = e ; } return offset ; }

Copies the contents of this immutable collection into the specified array at the specified
offset. Returns {@code offset + size()}.

Copies the contents of this immutable collection into the specified array at the specified offset . Returns {


public static <T> Iterable<T> unmodifiableIterable(final Iterable<? extends T> iterable) {
    checkNotNull(iterable);
    if (iterable instanceof UnmodifiableIterable || iterable instanceof ImmutableCollection) {
      @SuppressWarnings("unchecked") // Since it's unmodifiable, the covariant cast is safe
      Iterable<T> result = (Iterable<T>) iterable;
      return result;
    }
    return new UnmodifiableIterable<>(iterable);
  }

Returns an unmodifiable view of {@code iterable}.


@Deprecated
  public static <E> Iterable<E> unmodifiableIterable(ImmutableCollection<E> iterable) {
    return checkNotNull(iterable);
  }

@ Deprecated public static < E > Iterable < E > unmodifiableIterable ( ImmutableCollection < E > iterable ) { return checkNotNull ( iterable ) ; }

Simply returns its argument.

@deprecated no need to use this
@since 10.0


public static int size(Iterable<?> iterable) {
    return (iterable instanceof Collection)
        ? ((Collection<?>) iterable).size()
        : Iterators.size(iterable.iterator());
  }

public static int size ( Iterable < ? > iterable ) { return ( iterable instanceof Collection ) ? ( ( Collection < ? > ) iterable ) . size ( ) : Iterators . size ( iterable . iterator ( ) ) ; }

Returns the number of elements in {@code iterable}.


@CanIgnoreReturnValue
  public static <T> boolean removeIf(Iterable<T> removeFrom, Predicate<? super T> predicate) {
    if (removeFrom instanceof RandomAccess && removeFrom instanceof List) {
      return removeIfFromRandomAccessList((List<T>) removeFrom, checkNotNull(predicate));
    }
    return Iterators.removeIf(removeFrom.iterator(), predicate);
  }

@ CanIgnoreReturnValue public static < T > boolean removeIf ( Iterable < T > removeFrom , Predicate < ? super T > predicate ) { if ( removeFrom instanceof RandomAccess && removeFrom instanceof List ) { return removeIfFromRandomAccessList ( ( List < T > ) removeFrom , checkNotNull ( predicate ) ) ; } return Iterators . removeIf ( removeFrom . iterator ( ) , predicate ) ; }

Removes, from an iterable, every element that satisfies the provided predicate.

<p>Removals may or may not happen immediately as each element is tested against the predicate.
The behavior of this method is not specified if {@code predicate} is dependent on {@code
removeFrom}.

@param removeFrom the iterable to (potentially) remove elements from
@param predicate a predicate that determines whether an element should be removed
@return {@code true} if any elements were removed from the iterable
@throws UnsupportedOperationException if the iterable does not support {@code remove()}.
@since 2.0

Removes from an iterable every element that satisfies the provided predicate .


public static boolean elementsEqual(Iterable<?> iterable1, Iterable<?> iterable2) {
    if (iterable1 instanceof Collection && iterable2 instanceof Collection) {
      Collection<?> collection1 = (Collection<?>) iterable1;
      Collection<?> collection2 = (Collection<?>) iterable2;
      if (collection1.size() != collection2.size()) {
        return false;
      }
    }
    return Iterators.elementsEqual(iterable1.iterator(), iterable2.iterator());
  }

public static boolean elementsEqual ( Iterable < ? > iterable1 , Iterable < ? > iterable2 ) { if ( iterable1 instanceof Collection && iterable2 instanceof Collection ) { Collection < ? > collection1 = ( Collection < ? > ) iterable1 ; Collection < ? > collection2 = ( Collection < ? > ) iterable2 ; if ( collection1 . size ( ) != collection2 . size ( ) ) { return false ; } } return Iterators . elementsEqual ( iterable1 . iterator ( ) , iterable2 . iterator ( ) ) ; }

Determines whether two iterables contain equal elements in the same order. More specifically,
this method returns {@code true} if {@code iterable1} and {@code iterable2} contain the same
number of elements and every element of {@code iterable1} is equal to the corresponding element
of {@code iterable2}.

Determines whether two iterables contain equal elements in the same order . More specifically this method returns {


public static <T> T getOnlyElement(Iterable<T> iterable) {
    return Iterators.getOnlyElement(iterable.iterator());
  }

public static < T > T getOnlyElement ( Iterable < T > iterable ) { return Iterators . getOnlyElement ( iterable . iterator ( ) ) ; }

Returns the single element contained in {@code iterable}.

Java 8 users: the {@code Stream} equivalent to this method is {@code
stream.collect(MoreCollectors.onlyElement())}.

@throws NoSuchElementException if the iterable is empty
@throws IllegalArgumentException if the iterable contains multiple elements

Returns the single element contained in { @code iterable } .


@NullableDecl
  public static <T> T getOnlyElement(Iterable<? extends T> iterable, @NullableDecl T defaultValue) {
    return Iterators.getOnlyElement(iterable.iterator(), defaultValue);
  }

@ NullableDecl public static < T > T getOnlyElement ( Iterable < ? extends T > iterable , @ NullableDecl T defaultValue ) { return Iterators . getOnlyElement ( iterable . iterator ( ) , defaultValue ) ; }

Returns the single element contained in {@code iterable}, or {@code defaultValue} if the
iterable is empty.

Java 8 users: the {@code Stream} equivalent to this method is {@code
stream.collect(MoreCollectors.toOptional()).orElse(defaultValue)}.

@throws IllegalArgumentException if the iterator contains multiple elements

Returns the single element contained in { @code iterable } or { @code defaultValue } if the iterable is empty .


@GwtIncompatible // Array.newInstance(Class, int)
  public static <T> T[] toArray(Iterable<? extends T> iterable, Class<T> type) {
    return toArray(iterable, ObjectArrays.newArray(type, 0));
  }

@
GwtIncompatible
// Array.newInstance(Class, int)
public
static
<
T
>
T
[
]
toArray
(
Iterable
<
extends
T
>
iterable
,
Class
<
T
>
type
)
{
return
toArray
(
iterable
,
ObjectArrays
.
newArray
(
type
,
0
)
)
;
}

Copies an iterable's elements into an array.

@param iterable the iterable to copy
@param type the type of the elements
@return a newly-allocated array into which all the elements of the iterable have been copied

Copies an iterable s elements into an array .


private static <E> Collection<E> castOrCopyToCollection(Iterable<E> iterable) {
    return (iterable instanceof Collection)
        ? (Collection<E>) iterable
        : Lists.newArrayList(iterable.iterator());
  }

private static < E > Collection < E > castOrCopyToCollection ( Iterable < E > iterable ) { return ( iterable instanceof Collection ) ? ( Collection < E > ) iterable : Lists . newArrayList ( iterable . iterator ( ) ) ; }

Converts an iterable into a collection. If the iterable is already a collection, it is
returned. Otherwise, an {@link java.util.ArrayList} is created with the contents of the
iterable in the same iteration order.

Converts an iterable into a collection . If the iterable is already a collection it is returned . Otherwise an {


@CanIgnoreReturnValue
  public static <T> boolean addAll(Collection<T> addTo, Iterable<? extends T> elementsToAdd) {
    if (elementsToAdd instanceof Collection) {
      Collection<? extends T> c = Collections2.cast(elementsToAdd);
      return addTo.addAll(c);
    }
    return Iterators.addAll(addTo, checkNotNull(elementsToAdd).iterator());
  }

@ CanIgnoreReturnValue public static < T > boolean addAll ( Collection < T > addTo , Iterable < ? extends T > elementsToAdd ) { if ( elementsToAdd instanceof Collection ) { Collection < ? extends T > c = Collections2 . cast ( elementsToAdd ) ; return addTo . addAll ( c ) ; } return Iterators . addAll ( addTo , checkNotNull ( elementsToAdd ) . iterator ( ) ) ; }

Adds all elements in {@code iterable} to {@code collection}.

@return {@code true} if {@code collection} was modified as a result of this operation.

Adds all elements in { @code iterable } to { @code collection } .


public static int frequency(Iterable<?> iterable, @NullableDecl Object element) {
    if ((iterable instanceof Multiset)) {
      return ((Multiset<?>) iterable).count(element);
    } else if ((iterable instanceof Set)) {
      return ((Set<?>) iterable).contains(element) ? 1 : 0;
    }
    return Iterators.frequency(iterable.iterator(), element);
  }

public static int frequency ( Iterable < ? > iterable , @ NullableDecl Object element ) { if ( ( iterable instanceof Multiset ) ) { return ( ( Multiset < ? > ) iterable ) . count ( element ) ; } else if ( ( iterable instanceof Set ) ) { return ( ( Set < ? > ) iterable ) . contains ( element ) ? 1 : 0 ; } return Iterators . frequency ( iterable . iterator ( ) , element ) ; }

Returns the number of elements in the specified iterable that equal the specified object. This
implementation avoids a full iteration when the iterable is a {@link Multiset} or {@link Set}.

Java 8 users: In most cases, the {@code Stream} equivalent of this method is {@code
stream.filter(element::equals).count()}. If {@code element} might be null, use {@code
stream.filter(Predicate.isEqual(element)).count()} instead.

@see java.util.Collections#frequency(Collection, Object) Collections.frequency(Collection,
Object)

Returns the number of elements in the specified iterable that equal the specified object . This implementation avoids a full iteration when the iterable is a { @link Multiset } or { @link Set } .


public static <T> Iterable<T> cycle(final Iterable<T> iterable) {
    checkNotNull(iterable);
    return new FluentIterable<T>() {
      @Override
      public Iterator<T> iterator() {
        return Iterators.cycle(iterable);
      }

      @Override
      public String toString() {
        return iterable.toString() + " (cycled)";
      }
    };
  }

public
static
<
T
>
Iterable
<
T
>
cycle
(
final
Iterable
<
T
>
iterable
)
{
checkNotNull
(
iterable
)
;
return
new
FluentIterable
<
T
>
(
)
{
@
Override
public
Iterator
<
T
>
iterator
(
)
{
return
Iterators
.
cycle
(
iterable
)
;
}
@
Override
public
String
toString
(
)
{
return
iterable
.
toString
(
)
+
" (cycled)"
;
}
}
;
}

Returns an iterable whose iterators cycle indefinitely over the elements of {@code iterable}.

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

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

To cycle over the iterable {@code n} times, use the following: {@code
Iterables.concat(Collections.nCopies(n, iterable))}

Java 8 users: The {@code Stream} equivalent of this method is {@code
Stream.generate(() -> iterable).flatMap(Streams::stream)}.

Returns an iterable whose iterators cycle indefinitely over the elements of { @code iterable } .


public static <T> Iterable<T> concat(
      Iterable<? extends T> a, Iterable<? extends T> b, Iterable<? extends T> c) {
    return FluentIterable.concat(a, b, c);
  }

public static < T > Iterable < T > concat ( Iterable < ? extends T > a , Iterable < ? extends T > b , Iterable < ? extends T > c ) { return FluentIterable . concat ( a , b , c ) ; }

Combines three iterables into a single iterable. The returned iterable has an iterator that
traverses the elements in {@code a}, followed by the elements in {@code b}, followed by the
elements in {@code c}. The source iterators are not polled until necessary.

The returned iterable's iterator supports {@code remove()} when the corresponding input
iterator supports it.

Java 8 users: The {@code Stream} equivalent of this method is {@code
Streams.concat(a, b, c)}.

Combines three iterables into a single iterable . The returned iterable has an iterator that traverses the elements in { @code a } followed by the elements in { @code b } followed by the elements in { @code c } . The source iterators are not polled until necessary .


@SafeVarargs
  public static <T> Iterable<T> concat(Iterable<? extends T>... inputs) {
    return FluentIterable.concat(inputs);
  }

@ SafeVarargs public static < T > Iterable < T > concat ( Iterable < ? extends T > ... inputs ) { return FluentIterable . concat ( inputs ) ; }

Combines multiple iterables into a single iterable. The returned iterable has an iterator that
traverses the elements of each iterable in {@code inputs}. The input iterators are not polled
until necessary.

The returned iterable's iterator supports {@code remove()} when the corresponding input
iterator supports it.

Java 8 users: The {@code Stream} equivalent of this method is {@code
Streams.concat(...)}.

@throws NullPointerException if any of the provided iterables is null

Combines multiple iterables into a single iterable . The returned iterable has an iterator that traverses the elements of each iterable in { @code inputs } . The input iterators are not polled until necessary .


public static <T> Iterable<List<T>> partition(final Iterable<T> iterable, final int size) {
    checkNotNull(iterable);
    checkArgument(size > 0);
    return new FluentIterable<List<T>>() {
      @Override
      public Iterator<List<T>> iterator() {
        return Iterators.partition(iterable.iterator(), size);
      }
    };
  }

public static < T > Iterable < List < T > > partition ( final Iterable < T > iterable , final int size ) { checkNotNull ( iterable ) ; checkArgument ( size > 0 ) ; return new FluentIterable < List < T > > ( ) { @ Override public Iterator < List < T > > iterator ( ) { return Iterators . partition ( iterable . iterator ( ) , size ) ; } } ; }

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

Iterators returned by the returned iterable do not support the {@link Iterator#remove()}
method. The returned lists implement {@link RandomAccess}, whether or not the input list does.

Note: if {@code iterable} is a {@link List}, use {@link Lists#partition(List, int)}
instead.

@param iterable the iterable to return a partitioned view of
@param size the desired size of each partition (the last may be smaller)
@return an iterable of unmodifiable lists containing the elements of {@code iterable} divided
into partitions
@throws IllegalArgumentException if {@code size} is nonpositive

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


@SuppressWarnings("unchecked")
  @GwtIncompatible // Class.isInstance
  public static <T> Iterable<T> filter(final Iterable<?> unfiltered, final Class<T> desiredType) {
    checkNotNull(unfiltered);
    checkNotNull(desiredType);
    return (Iterable<T>) filter(unfiltered, Predicates.instanceOf(desiredType));
  }

@
SuppressWarnings
(
"unchecked"
)
@
GwtIncompatible
// Class.isInstance
public
static
<
T
>
Iterable
<
T
>
filter
(
final
Iterable
<
>
unfiltered
,
final
Class
<
T
>
desiredType
)
{
checkNotNull
(
unfiltered
)
;
checkNotNull
(
desiredType
)
;
return
(
Iterable
<
T
>
)
filter
(
unfiltered
,
Predicates
.
instanceOf
(
desiredType
)
)
;
}

Returns a view of {@code unfiltered} containing all elements that are of the type {@code
desiredType}. The returned iterable's iterator does not support {@code remove()}.

{@code Stream} equivalent: {@code stream.filter(type::isInstance).map(type::cast)}.
This does perform a little more work than necessary, so another option is to insert an
unchecked cast at some later point:

{@code @SuppressWarnings("unchecked") // safe because of ::isInstance check
ImmutableList<NewType> result =
(ImmutableList) stream.filter(NewType.class::isInstance).collect(toImmutableList());}

Returns a view of { @code unfiltered } containing all elements that are of the type { @code desiredType } . The returned iterable s iterator does not support { @code remove () } .


public static <T> boolean any(Iterable<T> iterable, Predicate<? super T> predicate) {
    return Iterators.any(iterable.iterator(), predicate);
  }

public static < T > boolean any ( Iterable < T > iterable , Predicate < ? super T > predicate ) { return Iterators . any ( iterable . iterator ( ) , predicate ) ; }

Returns {@code true} if any element in {@code iterable} satisfies the predicate.

{@code Stream} equivalent: {@link Stream#anyMatch}.

Returns { @code true } if any element in { @code iterable } satisfies the predicate .


public static <T> boolean all(Iterable<T> iterable, Predicate<? super T> predicate) {
    return Iterators.all(iterable.iterator(), predicate);
  }

public static < T > boolean all ( Iterable < T > iterable , Predicate < ? super T > predicate ) { return Iterators . all ( iterable . iterator ( ) , predicate ) ; }

Returns {@code true} if every element in {@code iterable} satisfies the predicate. If {@code
iterable} is empty, {@code true} is returned.

{@code Stream} equivalent: {@link Stream#allMatch}.

Returns { @code true } if every element in { @code iterable } satisfies the predicate . If { @code iterable } is empty { @code true } is returned .


public static <T> Optional<T> tryFind(Iterable<T> iterable, Predicate<? super T> predicate) {
    return Iterators.tryFind(iterable.iterator(), predicate);
  }

public static < T > Optional < T > tryFind ( Iterable < T > iterable , Predicate < ? super T > predicate ) { return Iterators . tryFind ( iterable . iterator ( ) , predicate ) ; }

Returns an {@link Optional} containing the first element in {@code iterable} that satisfies the
given predicate, if such an element exists.

Warning: avoid using a {@code predicate} that matches {@code null}. If {@code null}
is matched in {@code iterable}, a NullPointerException will be thrown.

{@code Stream} equivalent: {@code stream.filter(predicate).findFirst()}

@since 11.0

Returns an { @link Optional } containing the first element in { @code iterable } that satisfies the given predicate if such an element exists .


public static <T> int indexOf(Iterable<T> iterable, Predicate<? super T> predicate) {
    return Iterators.indexOf(iterable.iterator(), predicate);
  }

public static < T > int indexOf ( Iterable < T > iterable , Predicate < ? super T > predicate ) { return Iterators . indexOf ( iterable . iterator ( ) , predicate ) ; }

Returns the index in {@code iterable} of the first element that satisfies the provided {@code
predicate}, or {@code -1} if the Iterable has no such elements.

<p>More formally, returns the lowest index {@code i} such that {@code
predicate.apply(Iterables.get(iterable, i))} returns {@code true}, or {@code -1} if there is no
such index.

@since 2.0

Returns the index in { @code iterable } of the first element that satisfies the provided { @code predicate } or { @code - 1 } if the Iterable has no such elements .


public static <T> T get(Iterable<T> iterable, int position) {
    checkNotNull(iterable);
    return (iterable instanceof List)
        ? ((List<T>) iterable).get(position)
        : Iterators.get(iterable.iterator(), position);
  }

public static < T > T get ( Iterable < T > iterable , int position ) { checkNotNull ( iterable ) ; return ( iterable instanceof List ) ? ( ( List < T > ) iterable ) . get ( position ) : Iterators . get ( iterable . iterator ( ) , position ) ; }

Returns the element at the specified position in an iterable.

{@code Stream} equivalent: {@code stream.skip(position).findFirst().get()} (throws
{@code NoSuchElementException} if out of bounds)

@param position position of the element to return
@return the element at the specified position in {@code iterable}
@throws IndexOutOfBoundsException if {@code position} is negative or greater than or equal to
the size of {@code iterable}

Returns the element at the specified position in an iterable .


@NullableDecl
  public static <T> T get(
      Iterable<? extends T> iterable, int position, @NullableDecl T defaultValue) {
    checkNotNull(iterable);
    Iterators.checkNonnegative(position);
    if (iterable instanceof List) {
      List<? extends T> list = Lists.cast(iterable);
      return (position < list.size()) ? list.get(position) : defaultValue;
    } else {
      Iterator<? extends T> iterator = iterable.iterator();
      Iterators.advance(iterator, position);
      return Iterators.getNext(iterator, defaultValue);
    }
  }

@ NullableDecl public static < T > T get ( Iterable < ? extends T > iterable , int position , @ NullableDecl T defaultValue ) { checkNotNull ( iterable ) ; Iterators . checkNonnegative ( position ) ; if ( iterable instanceof List ) { List < ? extends T > list = Lists . cast ( iterable ) ; return ( position < list . size ( ) ) ? list . get ( position ) : defaultValue ; } else { Iterator < ? extends T > iterator = iterable . iterator ( ) ; Iterators . advance ( iterator , position ) ; return Iterators . getNext ( iterator , defaultValue ) ; } }

Returns the element at the specified position in an iterable or a default value otherwise.

{@code Stream} equivalent: {@code
stream.skip(position).findFirst().orElse(defaultValue)} (returns the default value if the index
is out of bounds)

@param position position of the element to return
@param defaultValue the default value to return if {@code position} is greater than or equal to
the size of the iterable
@return the element at the specified position in {@code iterable} or {@code defaultValue} if
{@code iterable} contains fewer than {@code position + 1} elements.
@throws IndexOutOfBoundsException if {@code position} is negative
@since 4.0

Returns the element at the specified position in an iterable or a default value otherwise .


@NullableDecl
  public static <T> T getFirst(Iterable<? extends T> iterable, @NullableDecl T defaultValue) {
    return Iterators.getNext(iterable.iterator(), defaultValue);
  }

@ NullableDecl public static < T > T getFirst ( Iterable < ? extends T > iterable , @ NullableDecl T defaultValue ) { return Iterators . getNext ( iterable . iterator ( ) , defaultValue ) ; }

Returns the first element in {@code iterable} or {@code defaultValue} if the iterable is empty.
The {@link Iterators} analog to this method is {@link Iterators#getNext}.

If no default value is desired (and the caller instead wants a {@link
NoSuchElementException} to be thrown), it is recommended that {@code
iterable.iterator().next()} is used instead.

To get the only element in a single-element {@code Iterable}, consider using {@link
#getOnlyElement(Iterable)} or {@link #getOnlyElement(Iterable, Object)} instead.

{@code Stream} equivalent: {@code stream.findFirst().orElse(defaultValue)}

@param defaultValue the default value to return if the iterable is empty
@return the first element of {@code iterable} or the default value
@since 7.0

Returns the first element in { @code iterable } or { @code defaultValue } if the iterable is empty . The { @link Iterators } analog to this method is { @link Iterators#getNext } .


public static <T> T getLast(Iterable<T> iterable) {
    // TODO(kevinb): Support a concurrently modified collection?
    if (iterable instanceof List) {
      List<T> list = (List<T>) iterable;
      if (list.isEmpty()) {
        throw new NoSuchElementException();
      }
      return getLastInNonemptyList(list);
    }

    return Iterators.getLast(iterable.iterator());
  }

Returns the last element of {@code iterable}. If {@code iterable} is a {@link List} with {@link
RandomAccess} support, then this operation is guaranteed to be {@code O(1)}.

{@code Stream} equivalent: {@link Streams#findLast Streams.findLast(stream).get()}

@return the last element of {@code iterable}
@throws NoSuchElementException if the iterable is empty

Returns the last element of { @code iterable } . If { @code iterable } is a { @link List } with { @link RandomAccess } support then this operation is guaranteed to be { @code O ( 1 ) } .


public static boolean isEmpty(Iterable<?> iterable) {
    if (iterable instanceof Collection) {
      return ((Collection<?>) iterable).isEmpty();
    }
    return !iterable.iterator().hasNext();
  }

public static boolean isEmpty ( Iterable < ? > iterable ) { if ( iterable instanceof Collection ) { return ( ( Collection < ? > ) iterable ) . isEmpty ( ) ; } return ! iterable . iterator ( ) . hasNext ( ) ; }

Determines if the given iterable contains no elements.

There is no precise {@link Iterator} equivalent to this method, since one can only ask an
iterator whether it has any elements remaining (which one does using {@link
Iterator#hasNext}).

{@code Stream} equivalent: {@code !stream.findAny().isPresent()}

@return {@code true} if the iterable contains no elements

Determines if the given iterable contains no elements .


@Beta
  public static <T> Iterable<T> mergeSorted(
      final Iterable<? extends Iterable<? extends T>> iterables,
      final Comparator<? super T> comparator) {
    checkNotNull(iterables, "iterables");
    checkNotNull(comparator, "comparator");
    Iterable<T> iterable =
        new FluentIterable<T>() {
          @Override
          public Iterator<T> iterator() {
            return Iterators.mergeSorted(
                Iterables.transform(iterables, Iterables.<T>toIterator()), comparator);
          }
        };
    return new UnmodifiableIterable<>(iterable);
  }

@ Beta public static < T > Iterable < T > mergeSorted ( final Iterable < ? extends Iterable < ? extends T > > iterables , final Comparator < ? super T > comparator ) { checkNotNull ( iterables , "iterables" ) ; checkNotNull ( comparator , "comparator" ) ; Iterable < T > iterable = new FluentIterable < T > ( ) { @ Override public Iterator < T > iterator ( ) { return Iterators . mergeSorted ( Iterables . transform ( iterables , Iterables . < T > toIterator ( ) ) , comparator ) ; } } ; return new UnmodifiableIterable <> ( iterable ) ; }

Returns an iterable over the merged contents of all given {@code iterables}. Equivalent entries
will not be de-duplicated.

Callers must ensure that the source {@code iterables} are in non-descending order as this
method does not sort its input.

For any equivalent elements across all {@code iterables}, it is undefined which element is
returned first.

@since 11.0

Returns an iterable over the merged contents of all given { @code iterables } . Equivalent entries will not be de - duplicated .


static <T> Function<Iterable<? extends T>, Iterator<? extends T>> toIterator() {
    return new Function<Iterable<? extends T>, Iterator<? extends T>>() {
      @Override
      public Iterator<? extends T> apply(Iterable<? extends T> iterable) {
        return iterable.iterator();
      }
    };
  }

static < T > Function < Iterable < ? extends T > , Iterator < ? extends T > > toIterator ( ) { return new Function < Iterable < ? extends T > , Iterator < ? extends T > > ( ) { @ Override public Iterator < ? extends T > apply ( Iterable < ? extends T > iterable ) { return iterable . iterator ( ) ; } } ; }


@Deprecated
  public static <T> UnmodifiableIterator<T> unmodifiableIterator(UnmodifiableIterator<T> iterator) {
    return checkNotNull(iterator);
  }

@ Deprecated public static < T > UnmodifiableIterator < T > unmodifiableIterator ( UnmodifiableIterator < T > iterator ) { return checkNotNull ( iterator ) ; }

Simply returns its argument.

@deprecated no need to use this
@since 10.0


public static int size(Iterator<?> iterator) {
    long count = 0L;
    while (iterator.hasNext()) {
      iterator.next();
      count++;
    }
    return Ints.saturatedCast(count);
  }

public static int size ( Iterator < ? > iterator ) { long count = 0L ; while ( iterator . hasNext ( ) ) { iterator . next ( ) ; count ++ ; } return Ints . saturatedCast ( count ) ; }

Returns the number of elements remaining in {@code iterator}. The iterator will be left
exhausted: its {@code hasNext()} method will return {@code false}.


public static boolean contains(Iterator<?> iterator, @NullableDecl Object element) {
    if (element == null) {
      while (iterator.hasNext()) {
        if (iterator.next() == null) {
          return true;
        }
      }
    } else {
      while (iterator.hasNext()) {
        if (element.equals(iterator.next())) {
          return true;
        }
      }
    }
    return false;
  }

public static boolean contains ( Iterator < ? > iterator , @ NullableDecl Object element ) { if ( element == null ) { while ( iterator . hasNext ( ) ) { if ( iterator . next ( ) == null ) { return true ; } } } else { while ( iterator . hasNext ( ) ) { if ( element . equals ( iterator . next ( ) ) ) { return true ; } } } return false ; }

Returns {@code true} if {@code iterator} contains {@code element}.


@CanIgnoreReturnValue
  public static boolean removeAll(Iterator<?> removeFrom, Collection<?> elementsToRemove) {
    checkNotNull(elementsToRemove);
    boolean result = false;
    while (removeFrom.hasNext()) {
      if (elementsToRemove.contains(removeFrom.next())) {
        removeFrom.remove();
        result = true;
      }
    }
    return result;
  }

@ CanIgnoreReturnValue public static boolean removeAll ( Iterator < ? > removeFrom , Collection < ? > elementsToRemove ) { checkNotNull ( elementsToRemove ) ; boolean result = false ; while ( removeFrom . hasNext ( ) ) { if ( elementsToRemove . contains ( removeFrom . next ( ) ) ) { removeFrom . remove ( ) ; result = true ; } } return result ; }

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

@param removeFrom the iterator to (potentially) remove elements from
@param elementsToRemove the elements to remove
@return {@code true} if any element was removed from {@code iterator}

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


@CanIgnoreReturnValue
  public static <T> boolean removeIf(Iterator<T> removeFrom, Predicate<? super T> predicate) {
    checkNotNull(predicate);
    boolean modified = false;
    while (removeFrom.hasNext()) {
      if (predicate.apply(removeFrom.next())) {
        removeFrom.remove();
        modified = true;
      }
    }
    return modified;
  }

@ CanIgnoreReturnValue public static < T > boolean removeIf ( Iterator < T > removeFrom , Predicate < ? super T > predicate ) { checkNotNull ( predicate ) ; boolean modified = false ; while ( removeFrom . hasNext ( ) ) { if ( predicate . apply ( removeFrom . next ( ) ) ) { removeFrom . remove ( ) ; modified = true ; } } return modified ; }

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

@param removeFrom the iterator to (potentially) remove elements from
@param predicate a predicate that determines whether an element should be removed
@return {@code true} if any elements were removed from the iterator
@since 2.0

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


@CanIgnoreReturnValue
  public static boolean retainAll(Iterator<?> removeFrom, Collection<?> elementsToRetain) {
    checkNotNull(elementsToRetain);
    boolean result = false;
    while (removeFrom.hasNext()) {
      if (!elementsToRetain.contains(removeFrom.next())) {
        removeFrom.remove();
        result = true;
      }
    }
    return result;
  }

@ CanIgnoreReturnValue public static boolean retainAll ( Iterator < ? > removeFrom , Collection < ? > elementsToRetain ) { checkNotNull ( elementsToRetain ) ; boolean result = false ; while ( removeFrom . hasNext ( ) ) { if ( ! elementsToRetain . contains ( removeFrom . next ( ) ) ) { removeFrom . remove ( ) ; result = true ; } } return result ; }

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

@param removeFrom the iterator to (potentially) remove elements from
@param elementsToRetain the elements to retain
@return {@code true} if any element was removed from {@code iterator}

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


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

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

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

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

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


@NullableDecl
  public static <T> T getOnlyElement(Iterator<? extends T> iterator, @NullableDecl T defaultValue) {
    return iterator.hasNext() ? getOnlyElement(iterator) : defaultValue;
  }

@ NullableDecl public static < T > T getOnlyElement ( Iterator < ? extends T > iterator , @ NullableDecl T defaultValue ) { return iterator . hasNext ( ) ? getOnlyElement ( iterator ) : defaultValue ; }

Returns the single element contained in {@code iterator}, or {@code defaultValue} if the
iterator is empty.

@throws IllegalArgumentException if the iterator contains multiple elements. The state of the
iterator is unspecified.

Returns the single element contained in { @code iterator } or { @code defaultValue } if the iterator is empty .


@GwtIncompatible // Array.newInstance(Class, int)
  public static <T> T[] toArray(Iterator<? extends T> iterator, Class<T> type) {
    List<T> list = Lists.newArrayList(iterator);
    return Iterables.toArray(list, type);
  }

@
GwtIncompatible
// Array.newInstance(Class, int)
public
static
<
T
>
T
[
]
toArray
(
Iterator
<
extends
T
>
iterator
,
Class
<
T
>
type
)
{
List
<
T
>
list
=
Lists
.
newArrayList
(
iterator
)
;
return
Iterables
.
toArray
(
list
,
type
)
;
}

Copies an iterator's elements into an array. The iterator will be left exhausted: its {@code
hasNext()} method will return {@code false}.

@param iterator the iterator to copy
@param type the type of the elements
@return a newly-allocated array into which all the elements of the iterator have been copied

Copies an iterator s elements into an array . The iterator will be left exhausted : its { @code hasNext () } method will return { @code false } .


public static int frequency(Iterator<?> iterator, @NullableDecl Object element) {
    int count = 0;
    while (contains(iterator, element)) {
      // Since it lives in the same class, we know contains gets to the element and then stops,
      // though that isn't currently publicly documented.
      count++;
    }
    return count;
  }

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

@see Collections#frequency

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


public static <T> Iterator<T> cycle(final Iterable<T> iterable) {
    checkNotNull(iterable);
    return new Iterator<T>() {
      Iterator<T> iterator = emptyModifiableIterator();

      @Override
      public boolean hasNext() {
        /*
         * Don't store a new Iterator until we know the user can't remove() the last returned
         * element anymore. Otherwise, when we remove from the old iterator, we may be invalidating
         * the new one. The result is a ConcurrentModificationException or other bad behavior.
         *
         * (If we decide that we really, really hate allocating two Iterators per cycle instead of
         * one, we can optimistically store the new Iterator and then be willing to throw it out if
         * the user calls remove().)
         */
        return iterator.hasNext() || iterable.iterator().hasNext();
      }

      @Override
      public T next() {
        if (!iterator.hasNext()) {
          iterator = iterable.iterator();
          if (!iterator.hasNext()) {
            throw new NoSuchElementException();
          }
        }
        return iterator.next();
      }

      @Override
      public void remove() {
        iterator.remove();
      }
    };
  }

Returns an iterator that cycles indefinitely over the elements of {@code iterable}.

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

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

Returns an iterator that cycles indefinitely over the elements of { @code iterable } .


private static <T> Iterator<T> consumingForArray(final T... elements) {
    return new UnmodifiableIterator<T>() {
      int index = 0;

      @Override
      public boolean hasNext() {
        return index < elements.length;
      }

      @Override
      public T next() {
        if (!hasNext()) {
          throw new NoSuchElementException();
        }
        T result = elements[index];
        elements[index] = null;
        index++;
        return result;
      }
    };
  }

private static < T > Iterator < T > consumingForArray ( final T ... elements ) { return new UnmodifiableIterator < T > ( ) { int index = 0 ; @ Override public boolean hasNext ( ) { return index < elements . length ; } @ Override public T next ( ) { if ( ! hasNext ( ) ) { throw new NoSuchElementException ( ) ; } T result = elements [ index ] ; elements [ index ] = null ; index ++ ; return result ; } } ; }

Returns an Iterator that walks the specified array, nulling out elements behind it. This can
avoid memory leaks when an element is no longer necessary.

<p>This is mainly just to avoid the intermediate ArrayDeque in ConsumingQueueIterator.

Returns an Iterator that walks the specified array nulling out elements behind it . This can avoid memory leaks when an element is no longer necessary .


public static <T> Iterator<T> concat(Iterator<? extends T> a, Iterator<? extends T> b) {
    checkNotNull(a);
    checkNotNull(b);
    return concat(consumingForArray(a, b));
  }

public static < T > Iterator < T > concat ( Iterator < ? extends T > a , Iterator < ? extends T > b ) { checkNotNull ( a ) ; checkNotNull ( b ) ; return concat ( consumingForArray ( a , b ) ) ; }

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

<p>The returned iterator supports {@code remove()} when the corresponding input iterator
supports it.

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


public static <T> Iterator<T> concat(Iterator<? extends T>... inputs) {
    return concatNoDefensiveCopy(Arrays.copyOf(inputs, inputs.length));
  }

public static < T > Iterator < T > concat ( Iterator < ? extends T > ... inputs ) { return concatNoDefensiveCopy ( Arrays . copyOf ( inputs , inputs . length ) ) ; }

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

<p>The returned iterator supports {@code remove()} when the corresponding input iterator
supports it.

@throws NullPointerException if any of the provided iterators is null

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


public static <T> Iterator<T> concat(Iterator<? extends Iterator<? extends T>> inputs) {
    return new ConcatenatedIterator<T>(inputs);
  }

public static < T > Iterator < T > concat ( Iterator < ? extends Iterator < ? extends T > > inputs ) { return new ConcatenatedIterator < T > ( inputs ) ; }

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

<p>The returned iterator supports {@code remove()} when the corresponding input iterator
supports it. The methods of the returned iterator may throw {@code NullPointerException} if any
of the input iterators is null.


static <T> Iterator<T> concatNoDefensiveCopy(Iterator<? extends T>... inputs) {
    for (Iterator<? extends T> input : checkNotNull(inputs)) {
      checkNotNull(input);
    }
    return concat(consumingForArray(inputs));
  }

static < T > Iterator < T > concatNoDefensiveCopy ( Iterator < ? extends T > ... inputs ) { for ( Iterator < ? extends T > input : checkNotNull ( inputs ) ) { checkNotNull ( input ) ; } return concat ( consumingForArray ( inputs ) ) ; }

Concats a varargs array of iterators without making a defensive copy of the array.

Concats a varargs array of iterators without making a defensive copy of the array .


public static <T> UnmodifiableIterator<List<T>> partition(Iterator<T> iterator, int size) {
    return partitionImpl(iterator, size, false);
  }

public static < T > UnmodifiableIterator < List < T > > partition ( Iterator < T > iterator , int size ) { return partitionImpl ( iterator , size , false ) ; }

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

<p>The returned lists implement {@link java.util.RandomAccess}.

@param iterator the iterator to return a partitioned view of
@param size the desired size of each partition (the last may be smaller)
@return an iterator of immutable lists containing the elements of {@code iterator} divided into
partitions
@throws IllegalArgumentException if {@code size} is nonpositive

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


public static <T> UnmodifiableIterator<List<T>> paddedPartition(Iterator<T> iterator, int size) {
    return partitionImpl(iterator, size, true);
  }

public static < T > UnmodifiableIterator < List < T > > paddedPartition ( Iterator < T > iterator , int size ) { return partitionImpl ( iterator , size , true ) ; }

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 {@code [a, b,
c, d, e]} with a partition size of 3 yields {@code [[a, b, c], [d, e, null]]} -- an outer
iterator containing two inner lists of three elements each, all in the original order.

<p>The returned lists implement {@link java.util.RandomAccess}.

@param iterator the iterator to return a partitioned view of
@param size the desired size of each partition
@return an iterator of immutable lists containing the elements of {@code iterator} divided into
partitions (the final iterable may have trailing null elements)
@throws IllegalArgumentException if {@code size} is nonpositive

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 { @code [ a b c d e ] } with a partition size of 3 yields { @code [[ a b c ] [ d e null ]] } -- an outer iterator containing two inner lists of three elements each all in the original order .


@SuppressWarnings("unchecked") // can cast to <T> because non-Ts are removed
  @GwtIncompatible // Class.isInstance
  public static <T> UnmodifiableIterator<T> filter(Iterator<?> unfiltered, Class<T> desiredType) {
    return (UnmodifiableIterator<T>) filter(unfiltered, instanceOf(desiredType));
  }

Returns a view of {@code unfiltered} containing all elements that are of the type {@code
desiredType}.


public static <T> boolean any(Iterator<T> iterator, Predicate<? super T> predicate) {
    return indexOf(iterator, predicate) != -1;
  }

public static < T > boolean any ( Iterator < T > iterator , Predicate < ? super T > predicate ) { return indexOf ( iterator , predicate ) != - 1 ; }

Returns {@code true} if one or more elements returned by {@code iterator} satisfy the given
predicate.


public static <T> boolean all(Iterator<T> iterator, Predicate<? super T> predicate) {
    checkNotNull(predicate);
    while (iterator.hasNext()) {
      T element = iterator.next();
      if (!predicate.apply(element)) {
        return false;
      }
    }
    return true;
  }

public static < T > boolean all ( Iterator < T > iterator , Predicate < ? super T > predicate ) { checkNotNull ( predicate ) ; while ( iterator . hasNext ( ) ) { T element = iterator . next ( ) ; if ( ! predicate . apply ( element ) ) { return false ; } } return true ; }

Returns {@code true} if every element returned by {@code iterator} satisfies the given
predicate. If {@code iterator} is empty, {@code true} is returned.


public static <T> T find(Iterator<T> iterator, Predicate<? super T> predicate) {
    checkNotNull(iterator);
    checkNotNull(predicate);
    while (iterator.hasNext()) {
      T t = iterator.next();
      if (predicate.apply(t)) {
        return t;
      }
    }
    throw new NoSuchElementException();
  }

public static < T > T find ( Iterator < T > iterator , Predicate < ? super T > predicate ) { checkNotNull ( iterator ) ; checkNotNull ( predicate ) ; while ( iterator . hasNext ( ) ) { T t = iterator . next ( ) ; if ( predicate . apply ( t ) ) { return t ; } } throw new NoSuchElementException ( ) ; }

Returns the first element in {@code 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 {@code hasNext()} method will return {@code false}. If it is
possible that <i>no</i> element will match, use {@link #tryFind} or {@link #find(Iterator,
Predicate, Object)} instead.

@throws NoSuchElementException if no element in {@code iterator} matches the given predicate

Returns the first element in { @code 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 { @code hasNext () } method will return { @code false } . If it is possible that <i > no< / i > element will match use { @link #tryFind } or { @link #find ( Iterator Predicate Object ) } instead .


@NullableDecl
  public static <T> T find(
      Iterator<? extends T> iterator,
      Predicate<? super T> predicate,
      @NullableDecl T defaultValue) {
    checkNotNull(iterator);
    checkNotNull(predicate);
    while (iterator.hasNext()) {
      T t = iterator.next();
      if (predicate.apply(t)) {
        return t;
      }
    }
    return defaultValue;
  }

@ NullableDecl public static < T > T find ( Iterator < ? extends T > iterator , Predicate < ? super T > predicate , @ NullableDecl T defaultValue ) { checkNotNull ( iterator ) ; checkNotNull ( predicate ) ; while ( iterator . hasNext ( ) ) { T t = iterator . next ( ) ; if ( predicate . apply ( t ) ) { return t ; } } return defaultValue ; }

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

@since 7.0

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


public static <T> Optional<T> tryFind(Iterator<T> iterator, Predicate<? super T> predicate) {
    checkNotNull(iterator);
    checkNotNull(predicate);
    while (iterator.hasNext()) {
      T t = iterator.next();
      if (predicate.apply(t)) {
        return Optional.of(t);
      }
    }
    return Optional.absent();
  }

public static < T > Optional < T > tryFind ( Iterator < T > iterator , Predicate < ? super T > predicate ) { checkNotNull ( iterator ) ; checkNotNull ( predicate ) ; while ( iterator . hasNext ( ) ) { T t = iterator . next ( ) ; if ( predicate . apply ( t ) ) { return Optional . of ( t ) ; } } return Optional . absent ( ) ; }

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

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

@since 11.0

Returns an { @link Optional } containing the first element in { @code iterator } that satisfies the given predicate if such an element exists . If no such element is found an empty { @link Optional } will be returned from this method and the iterator will be left exhausted : its { @code hasNext () } method will return { @code false } .


public static <T> T get(Iterator<T> iterator, int position) {
    checkNonnegative(position);
    int skipped = advance(iterator, position);
    if (!iterator.hasNext()) {
      throw new IndexOutOfBoundsException(
          "position ("
              + position
              + ") must be less than the number of elements that remained ("
              + skipped
              + ")");
    }
    return iterator.next();
  }

Advances {@code iterator} {@code position + 1} times, returning the element at the {@code
position}th position.

@param position position of the element to return
@return the element at the specified position in {@code iterator}
@throws IndexOutOfBoundsException if {@code position} is negative or greater than or equal to
the number of elements remaining in {@code iterator}

Advances { @code iterator } { @code position + 1 } times returning the element at the { @code position } th position .


@NullableDecl
  public static <T> T getNext(Iterator<? extends T> iterator, @NullableDecl T defaultValue) {
    return iterator.hasNext() ? iterator.next() : defaultValue;
  }

@ NullableDecl public static < T > T getNext ( Iterator < ? extends T > iterator , @ NullableDecl T defaultValue ) { return iterator . hasNext ( ) ? iterator . next ( ) : defaultValue ; }

Returns the next element in {@code iterator} or {@code defaultValue} if the iterator is empty.
The {@link Iterables} analog to this method is {@link Iterables#getFirst}.

@param defaultValue the default value to return if the iterator is empty
@return the next element of {@code iterator} or the default value
@since 7.0

Returns the next element in { @code iterator } or { @code defaultValue } if the iterator is empty . The { @link Iterables } analog to this method is { @link Iterables#getFirst } .


public static <T> T getLast(Iterator<T> iterator) {
    while (true) {
      T current = iterator.next();
      if (!iterator.hasNext()) {
        return current;
      }
    }
  }

public static < T > T getLast ( Iterator < T > iterator ) { while ( true ) { T current = iterator . next ( ) ; if ( ! iterator . hasNext ( ) ) { return current ; } } }

Advances {@code iterator} to the end, returning the last element.

@return the last element of {@code iterator}
@throws NoSuchElementException if the iterator is empty

Advances { @code iterator } to the end returning the last element .


@NullableDecl
  public static <T> T getLast(Iterator<? extends T> iterator, @NullableDecl T defaultValue) {
    return iterator.hasNext() ? getLast(iterator) : defaultValue;
  }

@ NullableDecl public static < T > T getLast ( Iterator < ? extends T > iterator , @ NullableDecl T defaultValue ) { return iterator . hasNext ( ) ? getLast ( iterator ) : defaultValue ; }

Advances {@code iterator} to the end, returning the last element or {@code defaultValue} if the
iterator is empty.

@param defaultValue the default value to return if the iterator is empty
@return the last element of {@code iterator}
@since 3.0

Advances { @code iterator } to the end returning the last element or { @code defaultValue } if the iterator is empty .


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(...)";
      }
    };
  }

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(...)" ; } } ; }

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

<p>The provided iterator must support {@link Iterator#remove()} or else the returned iterator
will fail on the first call to {@code next}.

@param iterator the iterator to remove and return elements from
@return an iterator that removes and returns elements from the supplied iterator
@since 2.0

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


@NullableDecl
  static <T> T pollNext(Iterator<T> iterator) {
    if (iterator.hasNext()) {
      T result = iterator.next();
      iterator.remove();
      return result;
    } else {
      return null;
    }
  }

@ NullableDecl static < T > T pollNext ( Iterator < T > iterator ) { if ( iterator . hasNext ( ) ) { T result = iterator . next ( ) ; iterator . remove ( ) ; return result ; } else { return null ; } }

Deletes and returns the next value from the iterator, or returns {@code null} if there is no
such value.

Deletes and returns the next value from the iterator or returns {


static void clear(Iterator<?> iterator) {
    checkNotNull(iterator);
    while (iterator.hasNext()) {
      iterator.next();
      iterator.remove();
    }
  }

static void clear ( Iterator < ? > iterator ) { checkNotNull ( iterator ) ; while ( iterator . hasNext ( ) ) { iterator . next ( ) ; iterator . remove ( ) ; } }

Clears the iterator using its remove method.

Clears the iterator using its remove method .


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

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

Returns an iterator containing the elements of {@code 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 {@link Arrays#asList(Object[])}, making this method unnecessary.

The {@code Iterable} equivalent of this method is either {@link Arrays#asList(Object[])},
{@link ImmutableList#copyOf(Object[])}}, or {@link ImmutableList#of}.

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


static <T> UnmodifiableListIterator<T> forArray(
      final T[] array, final int offset, int length, int index) {
    checkArgument(length >= 0);
    int end = offset + length;

    // Technically we should give a slightly more descriptive error on overflow
    Preconditions.checkPositionIndexes(offset, end, array.length);
    Preconditions.checkPositionIndex(index, length);
    if (length == 0) {
      return emptyListIterator();
    }
    return new ArrayItr<T>(array, offset, length, index);
  }

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

<p>The {@code Iterable} equivalent of this method is {@code
Arrays.asList(array).subList(offset, offset + length).listIterator(index)}.

Returns a list iterator containing the elements in the specified range of { @code array } in order starting at the specified index .


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();
      }
    };
  }

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 {@code Enumeration} to the {@code Iterator} interface.

This method has no equivalent in {@link Iterables} because viewing an {@code Enumeration} as
an {@code Iterable} is impossible. However, the contents can be copied into a collection
using {@link Collections#list}.

Adapts an { @code Enumeration } to the { @code Iterator } interface .


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();
      }
    };
  }

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 ( ) ; } } ; }

Adapts an {@code Iterator} to the {@code Enumeration} interface.

<p>The {@code Iterable} equivalent of this method is either {@link Collections#enumeration} (if
you have a {@link Collection}), or {@code Iterators.asEnumeration(collection.iterator())}.

Adapts an { @code Iterator } to the { @code Enumeration } interface .


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);
  }

Returns a {@code PeekingIterator} backed by the given iterator.

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

{@code
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 {@link PeekingIterator#remove()} method) will leave the iterator in an undefined
state.

The returned iterator does not support removal after peeking, as explained by {@link
PeekingIterator#remove()}.

Note: If the given iterator is already a {@code 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 {@code PeekingIterator} when the behavior of the implementation is known to
meet the contract guaranteed by this method.

There is no {@link Iterable} equivalent to this method, so use this method to wrap each
individual iterator as it is generated.

@param iterator the backing iterator. The {@link PeekingIterator} assumes ownership of this
iterator, so users should cease making direct calls to it after calling this method.
@return a peeking iterator backed by that iterator. Apart from the additional {@link
PeekingIterator#peek()} method, this iterator behaves exactly the same as {@code iterator}.

Returns a { @code PeekingIterator } backed by the given iterator .


@Deprecated
  public static <T> PeekingIterator<T> peekingIterator(PeekingIterator<T> iterator) {
    return checkNotNull(iterator);
  }

@ Deprecated public static < T > PeekingIterator < T > peekingIterator ( PeekingIterator < T > iterator ) { return checkNotNull ( iterator ) ; }

Simply returns its argument.

@deprecated no need to use this
@since 10.0


@Beta
  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>(iterators, comparator);
  }

@ Beta 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 > ( iterators , comparator ) ; }

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

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

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

@since 11.0

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


static <T> ListIterator<T> cast(Iterator<T> iterator) {
    return (ListIterator<T>) iterator;
  }

static < T > ListIterator < T > cast ( Iterator < T > iterator ) { return ( ListIterator < T > ) iterator ; }

Used to avoid http://bugs.sun.com/view_bug.do?bug_id=6558557

Used to avoid http : // bugs . sun . com / view_bug . do?bug_id = 6558557


@CanIgnoreReturnValue
  private NetworkConnections<N, E> addNodeInternal(N node) {
    NetworkConnections<N, E> connections = newConnections();
    checkState(nodeConnections.put(node, connections) == null);
    return connections;
  }

@ CanIgnoreReturnValue private NetworkConnections < N , E > addNodeInternal ( N node ) { NetworkConnections < N , E > connections = newConnections ( ) ; checkState ( nodeConnections . put ( node , connections ) == null ) ; return connections ; }

Adds {@code node} to the graph and returns the associated {@link NetworkConnections}.

@throws IllegalStateException if {@code node} is already present

Adds { @code node } to the graph and returns the associated { @link NetworkConnections } .


public static HostSpecifier fromValid(String specifier) {
    // Verify that no port was specified, and strip optional brackets from
    // IPv6 literals.
    final HostAndPort parsedHost = HostAndPort.fromString(specifier);
    Preconditions.checkArgument(!parsedHost.hasPort());
    final String host = parsedHost.getHost();

    // Try to interpret the specifier as an IP address. Note we build
    // the address rather than using the .is* methods because we want to
    // use InetAddresses.toUriString to convert the result to a string in
    // canonical form.
    InetAddress addr = null;
    try {
      addr = InetAddresses.forString(host);
    } catch (IllegalArgumentException e) {
      // It is not an IPv4 or IPv6 literal
    }

    if (addr != null) {
      return new HostSpecifier(InetAddresses.toUriString(addr));
    }

    // It is not any kind of IP address; must be a domain name or invalid.

    // TODO(user): different versions of this for different factories?
    final InternetDomainName domain = InternetDomainName.from(host);

    if (domain.hasPublicSuffix()) {
      return new HostSpecifier(domain.toString());
    }

    throw new IllegalArgumentException(
        "Domain name does not have a recognized public suffix: " + host);
  }

Returns a {@code HostSpecifier} built from the provided {@code specifier}, which is already
known to be valid. If the {@code specifier} might be invalid, use {@link #from(String)}
instead.

The specifier must be in one of these formats:

A domain name, like {@code google.com}

A IPv4 address string, like {@code 127.0.0.1}

An IPv6 address string with or without brackets, like {@code [2001:db8::1]} or {@code
2001:db8::1}

@throws IllegalArgumentException if the specifier is not valid.

Returns a { @code HostSpecifier } built from the provided { @code specifier } which is already known to be valid . If the { @code specifier } might be invalid use { @link #from ( String ) } instead .


public static HostSpecifier from(String specifier) throws ParseException {
    try {
      return fromValid(specifier);
    } catch (IllegalArgumentException e) {
      // Since the IAE can originate at several different points inside
      // fromValid(), we implement this method in terms of that one rather
      // than the reverse.

      ParseException parseException = new ParseException("Invalid host specifier: " + specifier, 0);
      parseException.initCause(e);
      throw parseException;
    }
  }

Attempts to return a {@code HostSpecifier} for the given string, throwing an exception if
parsing fails. Always use this method in preference to {@link #fromValid(String)} for a
specifier that is not already known to be valid.

@throws ParseException if the specifier is not valid.

Attempts to return a { @code HostSpecifier } for the given string throwing an exception if parsing fails . Always use this method in preference to { @link #fromValid ( String ) } for a specifier that is not already known to be valid .


public OutputStream openBufferedStream() throws IOException {
    OutputStream out = openStream();
    return (out instanceof BufferedOutputStream)
        ? (BufferedOutputStream) out
        : new BufferedOutputStream(out);
  }

public OutputStream openBufferedStream ( ) throws IOException { OutputStream out = openStream ( ) ; return ( out instanceof BufferedOutputStream ) ? ( BufferedOutputStream ) out : new BufferedOutputStream ( out ) ; }

Opens a new buffered {@link OutputStream} for writing to this sink. The returned stream is not
required to be a {@link BufferedOutputStream} in order to allow implementations to simply
delegate to {@link #openStream()} when the stream returned by that method does not benefit from
additional buffering (for example, a {@code ByteArrayOutputStream}). This method returns a new,
independent stream each time it is called.

<p>The caller is responsible for ensuring that the returned stream is closed.

@throws IOException if an I/O error occurs while opening the stream
@since 15.0 (in 14.0 with return type {@link BufferedOutputStream})

Opens a new buffered { @link OutputStream } for writing to this sink . The returned stream is not required to be a { @link BufferedOutputStream } in order to allow implementations to simply delegate to { @link #openStream () } when the stream returned by that method does not benefit from additional buffering ( for example a { @code ByteArrayOutputStream } ) . This method returns a new independent stream each time it is called .


public void write(byte[] bytes) throws IOException {
    checkNotNull(bytes);

    Closer closer = Closer.create();
    try {
      OutputStream out = closer.register(openStream());
      out.write(bytes);
      out.flush(); // https://code.google.com/p/guava-libraries/issues/detail?id=1330
    } catch (Throwable e) {
      throw closer.rethrow(e);
    } finally {
      closer.close();
    }
  }

Writes all the given bytes to this sink.

@throws IOException if an I/O occurs while writing to this sink

Writes all the given bytes to this sink .


@CanIgnoreReturnValue
  public long writeFrom(InputStream input) throws IOException {
    checkNotNull(input);

    Closer closer = Closer.create();
    try {
      OutputStream out = closer.register(openStream());
      long written = ByteStreams.copy(input, out);
      out.flush(); // https://code.google.com/p/guava-libraries/issues/detail?id=1330
      return written;
    } catch (Throwable e) {
      throw closer.rethrow(e);
    } finally {
      closer.close();
    }
  }

Writes all the bytes from the given {@code InputStream} to this sink. Does not close {@code
input}.

@return the number of bytes written
@throws IOException if an I/O occurs while reading from {@code input} or writing to this sink

Writes all the bytes from the given { @code InputStream } to this sink . Does not close { @code input } .


@CanIgnoreReturnValue
  @Override
  public int setCount(@Nullable E element, int count) {
    checkNonnegative(count, "count");

    Count existingCounter;
    int oldCount;
    if (count == 0) {
      existingCounter = backingMap.remove(element);
      oldCount = getAndSet(existingCounter, count);
    } else {
      existingCounter = backingMap.get(element);
      oldCount = getAndSet(existingCounter, count);

      if (existingCounter == null) {
        backingMap.put(element, new Count(count));
      }
    }

    size += (count - oldCount);
    return oldCount;
  }

@ CanIgnoreReturnValue @ Override public int setCount ( @ Nullable E element , int count ) { checkNonnegative ( count , "count" ) ; Count existingCounter ; int oldCount ; if ( count == 0 ) { existingCounter = backingMap . remove ( element ) ; oldCount = getAndSet ( existingCounter , count ) ; } else { existingCounter = backingMap . get ( element ) ; oldCount = getAndSet ( existingCounter , count ) ; if ( existingCounter == null ) { backingMap . put ( element , new Count ( count ) ) ; } } size += ( count - oldCount ) ; return oldCount ; }

Roughly a 33% performance improvement over AbstractMultiset.setCount().

Roughly a 33% performance improvement over AbstractMultiset . setCount () .


public static void verify(
      boolean expression,
      @Nullable String errorMessageTemplate,
      @Nullable Object @Nullable ... errorMessageArgs) {
    if (!expression) {
      throw new VerifyException(lenientFormat(errorMessageTemplate, errorMessageArgs));
    }
  }

public static void verify ( boolean expression , @ Nullable String errorMessageTemplate , @ Nullable Object @ Nullable . . . errorMessageArgs ) { if ( ! expression ) { throw new VerifyException ( lenientFormat ( errorMessageTemplate , errorMessageArgs ) ) ; } }

Ensures that {@code expression} is {@code true}, throwing a {@code VerifyException} with a
custom message otherwise.

@param expression a boolean expression
@param errorMessageTemplate a template for the exception message should the check fail. The
message is formed by replacing each {@code %s} placeholder in the template with an
argument. These are matched by position - the first {@code %s} gets {@code
errorMessageArgs[0]}, etc. Unmatched arguments will be appended to the formatted message in
square braces. Unmatched placeholders will be left as-is.
@param errorMessageArgs the arguments to be substituted into the message template. Arguments
are converted to strings using {@link String#valueOf(Object)}.
@throws VerifyException if {@code expression} is {@code false}
@see Preconditions#checkState Preconditions.checkState()

Ensures that { @code expression } is { @code true } throwing a { @code VerifyException } with a custom message otherwise .


public static void verify(boolean expression, @Nullable String errorMessageTemplate, char p1) {
    if (!expression) {
      throw new VerifyException(lenientFormat(errorMessageTemplate, p1));
    }
  }

public static void verify ( boolean expression , @ Nullable String errorMessageTemplate , char p1 ) { if ( ! expression ) { throw new VerifyException ( lenientFormat ( errorMessageTemplate , p1 ) ) ; } }

Ensures that {@code expression} is {@code true}, throwing a {@code VerifyException} with a
custom message otherwise.

<p>See {@link #verify(boolean, String, Object...)} for details.

@since 23.1 (varargs overload since 17.0)