signature:
public class ArrayBasedUnicodeEscaper { /** * 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 public final String escape ( String s ) { } }

implementation:
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 ;


signature:
public class ArrayBasedUnicodeEscaper { /** * 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 . */
@ Override protected final char [ ] escape ( int cp ) { } }

implementation: if ( cp < replacementsLength ) { char [ ] chars = replacements [ cp ] ; if ( chars != null ) { return chars ; } } if ( cp >= safeMin && cp <= safeMax ) { return null ; } return escapeUnsafe ( cp ) ;


signature:
public class ArrayBasedUnicodeEscaper { /** * / * Overridden for performance . */
@ Override protected final int nextEscapeIndex ( CharSequence csq , int index , int end ) { } }

implementation: while ( index < end ) { char c = csq . charAt ( index ) ; if ( ( c < replacementsLength && replacements [ c ] != null ) || c > safeMaxChar || c < safeMinChar ) { break ; } index ++ ; } return index ;


signature:
public class CharSource { /** * 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 */
public BufferedReader openBufferedStream ( ) throws IOException { } }

implementation: Reader reader = openStream ( ) ; return ( reader instanceof BufferedReader ) ? ( BufferedReader ) reader : new BufferedReader ( reader ) ;


signature:
public class CharSource { /** * 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 } .
 * < p > 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 .
 * < p > Note that for sources that implement { @ link # lengthIfKnown } to provide a more efficient
 * implementation , it is < i > possible < / i > that this method will return a different number of chars
 * than would be returned by reading all of the chars .
 * < p > 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 */
@ Beta public long length ( ) throws IOException { } }

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


signature:
public class CharSource { /** * 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 } */
@ CanIgnoreReturnValue public long copyTo ( CharSink sink ) throws IOException { } }

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


signature:
public class CharSource { /** * Reads the contents of this source as a string .
 * @ throws IOException if an I / O error occurs while reading from this source */
public String read ( ) throws IOException { } }

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


signature:
public class CharSource { /** * 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 */
@ NullableDecl public String readFirstLine ( ) throws IOException { } }

implementation: Closer closer = Closer . create ( ) ; try { BufferedReader reader = closer . register ( openBufferedStream ( ) ) ; return reader . readLine ( ) ; } catch ( Throwable e ) { throw closer . rethrow ( e ) ; } finally { closer . close ( ) ; }


signature:
public class CharSource { /** * 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 */
public ImmutableList < String > readLines ( ) throws IOException { } }

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


signature:
public class CharSource { /** * 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 .
 * < p > Note that , in cases where { @ code lengthIfKnown } returns zero , it is < i > possible < / i > 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 */
public boolean isEmpty ( ) throws IOException { } }

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


signature:
public class CharSource { /** * 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 ) } ) */
public static CharSource wrap ( CharSequence charSequence ) { } }

implementation: return charSequence instanceof String ? new StringCharSource ( ( String ) charSequence ) : new CharSequenceCharSource ( charSequence ) ;


signature:
public class ReaderInputStream { /** * buffer when possible . */
@ Override public int read ( byte [ ] b , int off , int len ) throws IOException { } }

implementation:
// 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 ) { doneFlushing = true ; startDraining ( false ) ; continue DRAINING ; } else if ( endOfInput ) { doneEncoding = true ; } else { readMoreChars ( ) ; } } else if ( result . isError ( ) ) { // Only reach here if a CharsetEncoder with non - REPLACE settings is used .
result . throwException ( ) ; return 0 ; // Not called .
} } }


signature:
public class ReaderInputStream { /** * Returns a new CharBuffer identical to buf , except twice the capacity . */
private static CharBuffer grow ( CharBuffer buf ) { } }

implementation: char [ ] copy = Arrays . copyOf ( buf . array ( ) , buf . capacity ( ) * 2 ) ; CharBuffer bigger = CharBuffer . wrap ( copy ) ; bigger . position ( buf . position ( ) ) ; bigger . limit ( buf . limit ( ) ) ; return bigger ;


signature:
public class ReaderInputStream { /** * Handle the case of underflow caused by needing more input characters . */
private void readMoreChars ( ) throws IOException { } }

implementation:
// 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 ) ; }


signature:
public class ReaderInputStream { /** * 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 void startDraining ( boolean overflow ) { } }

implementation: byteBuffer . flip ( ) ; if ( overflow && byteBuffer . remaining ( ) == 0 ) { byteBuffer = ByteBuffer . allocate ( byteBuffer . capacity ( ) * 2 ) ; } else { draining = true ; }


signature:
public class ReaderInputStream { /** * Copy as much of the byte buffer into the output array as possible , returning the ( positive )
 * number of characters copied . */
private int drain ( byte [ ] b , int off , int len ) { } }

implementation: int remaining = Math . min ( len , byteBuffer . remaining ( ) ) ; byteBuffer . get ( b , off , remaining ) ; return remaining ;


signature:
public class ForwardingNavigableMap { /** * 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 > standardLowerEntry ( K key ) { } }

implementation: return headMap ( key , false ) . lastEntry ( ) ;


signature:
public class ForwardingNavigableMap { /** * 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 > standardFloorEntry ( K key ) { } }

implementation: return headMap ( key , true ) . lastEntry ( ) ;


signature:
public class ForwardingNavigableMap { /** * 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 > standardCeilingEntry ( K key ) { } }

implementation: return tailMap ( key , true ) . firstEntry ( ) ;


signature:
public class ForwardingNavigableMap { /** * 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 Entry < K , V > standardHigherEntry ( K key ) { } }

implementation: return tailMap ( key , false ) . firstEntry ( ) ;


signature:
public class ForwardingNavigableMap { /** * 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 standardFirstKey ( ) { } }

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


signature:
public class ForwardingNavigableMap { /** * 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 K standardLastKey ( ) { } }

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


signature:
public class AbstractBaseGraph { /** * 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 . */
protected long edgeCount ( ) { } }

implementation:
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 ;


signature:
public class AbstractBaseGraph { /** * An implementation of { @ link BaseGraph # edges ( ) } defined in terms of { @ link # nodes ( ) } and { @ link
 * # successors ( Object ) } . */
@ Override public Set < EndpointPair < N > > edges ( ) { } }

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


signature:
public class ImmutableCollection { /** * Copies the contents of this immutable collection into the specified array at the specified
 * offset . Returns { @ code offset + size ( ) } . */
@ CanIgnoreReturnValue int copyIntoArray ( Object [ ] dst , int offset ) { } }

implementation: for ( E e : this ) { dst [ offset ++ ] = e ; } return offset ;


signature:
public class Iterables { /** * Returns an unmodifiable view of { @ code iterable } . */
public static < T > Iterable < T > unmodifiableIterable ( final Iterable < ? extends T > iterable ) { } }

implementation:
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 ) ;


signature:
public class Iterables { /** * Simply returns its argument .
 * @ deprecated no need to use this
 * @ since 10.0 */
@ Deprecated public static < E > Iterable < E > unmodifiableIterable ( ImmutableCollection < E > iterable ) { } }

implementation: return checkNotNull ( iterable ) ;


signature:
public class Iterables { /** * Returns the number of elements in { @ code iterable } . */
public static int size ( Iterable < ? > iterable ) { } }

implementation: return ( iterable instanceof Collection ) ? ( ( Collection < ? > ) iterable ) . size ( ) : Iterators . size ( iterable . iterator ( ) ) ;


signature:
public class Iterables { /** * 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 */
@ CanIgnoreReturnValue public static < T > boolean removeIf ( Iterable < T > removeFrom , Predicate < ? super T > predicate ) { } }

implementation: if ( removeFrom instanceof RandomAccess && removeFrom instanceof List ) { return removeIfFromRandomAccessList ( ( List < T > ) removeFrom , checkNotNull ( predicate ) ) ; } return Iterators . removeIf ( removeFrom . iterator ( ) , predicate ) ;


signature:
public class Iterables { /** * 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 } . */
public static boolean elementsEqual ( Iterable < ? > iterable1 , Iterable < ? > iterable2 ) { } }

implementation: 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 ( ) ) ;


signature:
public class Iterables { /** * Returns the single element contained in { @ code iterable } .
 * < p > < b > Java 8 users : < / b > 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 */
public static < T > T getOnlyElement ( Iterable < T > iterable ) { } }

implementation: return Iterators . getOnlyElement ( iterable . iterator ( ) ) ;


signature:
public class Iterables { /** * Returns the single element contained in { @ code iterable } , or { @ code defaultValue } if the
 * iterable is empty .
 * < p > < b > Java 8 users : < / b > the { @ code Stream } equivalent to this method is { @ code
 * stream . collect ( MoreCollectors . toOptional ( ) ) . orElse ( defaultValue ) } .
 * @ throws IllegalArgumentException if the iterator contains multiple elements */
@ NullableDecl public static < T > T getOnlyElement ( Iterable < ? extends T > iterable , @ NullableDecl T defaultValue ) { } }

implementation: return Iterators . getOnlyElement ( iterable . iterator ( ) , defaultValue ) ;


signature:
public class Iterables { /** * 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 */
@ GwtIncompatible // Array . newInstance ( Class , int )
public static < T > T [ ] toArray ( Iterable < ? extends T > iterable , Class < T > type ) { } }

implementation: return toArray ( iterable , ObjectArrays . newArray ( type , 0 ) ) ;


signature:
public class Iterables { /** * 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 . */
private static < E > Collection < E > castOrCopyToCollection ( Iterable < E > iterable ) { } }

implementation: return ( iterable instanceof Collection ) ? ( Collection < E > ) iterable : Lists . newArrayList ( iterable . iterator ( ) ) ;


signature:
public class Iterables { /** * Adds all elements in { @ code iterable } to { @ code collection } .
 * @ return { @ code true } if { @ code collection } was modified as a result of this operation . */
@ CanIgnoreReturnValue public static < T > boolean addAll ( Collection < T > addTo , Iterable < ? extends T > elementsToAdd ) { } }

implementation: if ( elementsToAdd instanceof Collection ) { Collection < ? extends T > c = Collections2 . cast ( elementsToAdd ) ; return addTo . addAll ( c ) ; } return Iterators . addAll ( addTo , checkNotNull ( elementsToAdd ) . iterator ( ) ) ;


signature:
public class Iterables { /** * 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 } .
 * < p > < b > Java 8 users : < / b > 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 ) */
public static int frequency ( Iterable < ? > iterable , @ NullableDecl Object element ) { } }

implementation: 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 ) ;


signature:
public class Iterables { /** * Returns an iterable whose iterators cycle indefinitely over the elements of { @ code iterable } .
 * < p > 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 .
 * < p > < b > Warning : < / b > 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 .
 * < p > To cycle over the iterable { @ code n } times , use the following : { @ code
 * Iterables . concat ( Collections . nCopies ( n , iterable ) ) }
 * < p > < b > Java 8 users : < / b > The { @ code Stream } equivalent of this method is { @ code
 * Stream . generate ( ( ) - > iterable ) . flatMap ( Streams : : stream ) } . */
public static < T > Iterable < T > cycle ( final Iterable < T > iterable ) { } }

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


signature:
public class Iterables { /** * 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 .
 * < p > The returned iterable ' s iterator supports { @ code remove ( ) } when the corresponding input
 * iterator supports it .
 * < p > < b > Java 8 users : < / b > The { @ code Stream } equivalent of this method is { @ code
 * Streams . concat ( a , b , c ) } . */
public static < T > Iterable < T > concat ( Iterable < ? extends T > a , Iterable < ? extends T > b , Iterable < ? extends T > c ) { } }

implementation: return FluentIterable . concat ( a , b , c ) ;


signature:
public class Iterables { /** * 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 .
 * < p > The returned iterable ' s iterator supports { @ code remove ( ) } when the corresponding input
 * iterator supports it .
 * < p > < b > Java 8 users : < / b > The { @ code Stream } equivalent of this method is { @ code
 * Streams . concat ( . . . ) } .
 * @ throws NullPointerException if any of the provided iterables is null */
@ SafeVarargs public static < T > Iterable < T > concat ( Iterable < ? extends T > ... inputs ) { } }

implementation: return FluentIterable . concat ( inputs ) ;


signature:
public class Iterables { /** * 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 .
 * < p > 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 .
 * < p > < b > Note : < / b > 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 */
public static < T > Iterable < List < T > > partition ( final Iterable < T > iterable , final int size ) { } }

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


signature:
public class Iterables { /** * 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 ( ) } .
 * < p > < b > { @ code Stream } equivalent : < / b > { @ 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 :
 * < pre >
 * { @ code @ SuppressWarnings ( " unchecked " ) / / safe because of : : isInstance check
 * ImmutableList < NewType > result =
 * ( ImmutableList ) stream . filter ( NewType . class : : isInstance ) . collect ( toImmutableList ( ) ) ; }
 * < / pre > */
@ SuppressWarnings ( "unchecked" ) @ GwtIncompatible // Class . isInstance
public static < T > Iterable < T > filter ( final Iterable < ? > unfiltered , final Class < T > desiredType ) { } }

implementation: checkNotNull ( unfiltered ) ; checkNotNull ( desiredType ) ; return ( Iterable < T > ) filter ( unfiltered , Predicates . instanceOf ( desiredType ) ) ;


signature:
public class Iterables { /** * Returns { @ code true } if any element in { @ code iterable } satisfies the predicate .
 * < p > < b > { @ code Stream } equivalent : < / b > { @ link Stream # anyMatch } . */
public static < T > boolean any ( Iterable < T > iterable , Predicate < ? super T > predicate ) { } }

implementation: return Iterators . any ( iterable . iterator ( ) , predicate ) ;


signature:
public class Iterables { /** * Returns { @ code true } if every element in { @ code iterable } satisfies the predicate . If { @ code
 * iterable } is empty , { @ code true } is returned .
 * < p > < b > { @ code Stream } equivalent : < / b > { @ link Stream # allMatch } . */
public static < T > boolean all ( Iterable < T > iterable , Predicate < ? super T > predicate ) { } }

implementation: return Iterators . all ( iterable . iterator ( ) , predicate ) ;


signature:
public class Iterables { /** * Returns an { @ link Optional } containing the first element in { @ code iterable } that satisfies the
 * given predicate , if such an element exists .
 * < p > < b > Warning : < / b > avoid using a { @ code predicate } that matches { @ code null } . If { @ code null }
 * is matched in { @ code iterable } , a NullPointerException will be thrown .
 * < p > < b > { @ code Stream } equivalent : < / b > { @ code stream . filter ( predicate ) . findFirst ( ) }
 * @ since 11.0 */
public static < T > Optional < T > tryFind ( Iterable < T > iterable , Predicate < ? super T > predicate ) { } }

implementation: return Iterators . tryFind ( iterable . iterator ( ) , predicate ) ;


signature:
public class Iterables { /** * 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 */
public static < T > int indexOf ( Iterable < T > iterable , Predicate < ? super T > predicate ) { } }

implementation: return Iterators . indexOf ( iterable . iterator ( ) , predicate ) ;


signature:
public class Iterables { /** * Returns the element at the specified position in an iterable .
 * < p > < b > { @ code Stream } equivalent : < / b > { @ 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 } */
public static < T > T get ( Iterable < T > iterable , int position ) { } }

implementation: checkNotNull ( iterable ) ; return ( iterable instanceof List ) ? ( ( List < T > ) iterable ) . get ( position ) : Iterators . get ( iterable . iterator ( ) , position ) ;


signature:
public class Iterables { /** * Returns the element at the specified position in an iterable or a default value otherwise .
 * < p > < b > { @ code Stream } equivalent : < / b > { @ 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 */
@ NullableDecl public static < T > T get ( Iterable < ? extends T > iterable , int position , @ NullableDecl T defaultValue ) { } }

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


signature:
public class Iterables { /** * 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 } .
 * < p > 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 .
 * < p > To get the only element in a single - element { @ code Iterable } , consider using { @ link
 * # getOnlyElement ( Iterable ) } or { @ link # getOnlyElement ( Iterable , Object ) } instead .
 * < p > < b > { @ code Stream } equivalent : < / b > { @ 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 */
@ NullableDecl public static < T > T getFirst ( Iterable < ? extends T > iterable , @ NullableDecl T defaultValue ) { } }

implementation: return Iterators . getNext ( iterable . iterator ( ) , defaultValue ) ;


signature:
public class Iterables { /** * 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 ) } .
 * < p > < b > { @ code Stream } equivalent : < / b > { @ link Streams # findLast Streams . findLast ( stream ) . get ( ) }
 * @ return the last element of { @ code iterable }
 * @ throws NoSuchElementException if the iterable is empty */
public static < T > T getLast ( Iterable < T > iterable ) { } }

implementation:
// 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 ( ) ) ;


signature:
public class Iterables { /** * Determines if the given iterable contains no elements .
 * < p > There is no precise { @ link Iterator } equivalent to this method , since one can only ask an
 * iterator whether it has any elements < i > remaining < / i > ( which one does using { @ link
 * Iterator # hasNext } ) .
 * < p > < b > { @ code Stream } equivalent : < / b > { @ code ! stream . findAny ( ) . isPresent ( ) }
 * @ return { @ code true } if the iterable contains no elements */
public static boolean isEmpty ( Iterable < ? > iterable ) { } }

implementation: if ( iterable instanceof Collection ) { return ( ( Collection < ? > ) iterable ) . isEmpty ( ) ; } return ! iterable . iterator ( ) . hasNext ( ) ;


signature:
public class Iterables { /** * Returns an iterable over the merged contents of all given { @ code iterables } . Equivalent entries
 * will not be de - duplicated .
 * < p > Callers must ensure that the source { @ code iterables } are in non - descending order as this
 * method does not sort its input .
 * < p > For any equivalent elements across all { @ code iterables } , it is undefined which element is
 * returned first .
 * @ since 11.0 */
@ Beta public static < T > Iterable < T > mergeSorted ( final Iterable < ? extends Iterable < ? extends T > > iterables , final Comparator < ? super T > comparator ) { } }

implementation: 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 ) ;


signature:
public class Iterables { /** * Useful as a public method ? */
static < T > Function < Iterable < ? extends T > , Iterator < ? extends T > > toIterator ( ) { } }

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


signature:
public class Iterators { /** * Simply returns its argument .
 * @ deprecated no need to use this
 * @ since 10.0 */
@ Deprecated public static < T > UnmodifiableIterator < T > unmodifiableIterator ( UnmodifiableIterator < T > iterator ) { } }

implementation: return checkNotNull ( iterator ) ;


signature:
public class Iterators { /** * 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 int size ( Iterator < ? > iterator ) { } }

implementation: long count = 0L ; while ( iterator . hasNext ( ) ) { iterator . next ( ) ; count ++ ; } return Ints . saturatedCast ( count ) ;


signature:
public class Iterators { /** * Returns { @ code true } if { @ code iterator } contains { @ code element } . */
public static boolean contains ( Iterator < ? > iterator , @ NullableDecl Object element ) { } }

implementation: 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 ;


signature:
public class Iterators { /** * 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 } */
@ CanIgnoreReturnValue public static boolean removeAll ( Iterator < ? > removeFrom , Collection < ? > elementsToRemove ) { } }

implementation: checkNotNull ( elementsToRemove ) ; boolean result = false ; while ( removeFrom . hasNext ( ) ) { if ( elementsToRemove . contains ( removeFrom . next ( ) ) ) { removeFrom . remove ( ) ; result = true ; } } return result ;


signature:
public class Iterators { /** * 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 */
@ CanIgnoreReturnValue public static < T > boolean removeIf ( Iterator < T > removeFrom , Predicate < ? super T > predicate ) { } }

implementation: checkNotNull ( predicate ) ; boolean modified = false ; while ( removeFrom . hasNext ( ) ) { if ( predicate . apply ( removeFrom . next ( ) ) ) { removeFrom . remove ( ) ; modified = true ; } } return modified ;


signature:
public class Iterators { /** * 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 } */
@ CanIgnoreReturnValue public static boolean retainAll ( Iterator < ? > removeFrom , Collection < ? > elementsToRetain ) { } }

implementation: checkNotNull ( elementsToRetain ) ; boolean result = false ; while ( removeFrom . hasNext ( ) ) { if ( ! elementsToRetain . contains ( removeFrom . next ( ) ) ) { removeFrom . remove ( ) ; result = true ; } } return result ;


signature:
public class Iterators { /** * 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 . */
public static boolean elementsEqual ( Iterator < ? > iterator1 , Iterator < ? > iterator2 ) { } }

implementation: 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 ( ) ;


signature:
public class Iterators { /** * 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 . */
@ NullableDecl public static < T > T getOnlyElement ( Iterator < ? extends T > iterator , @ NullableDecl T defaultValue ) { } }

implementation: return iterator . hasNext ( ) ? getOnlyElement ( iterator ) : defaultValue ;


signature:
public class Iterators { /** * 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 */
@ GwtIncompatible // Array . newInstance ( Class , int )
public static < T > T [ ] toArray ( Iterator < ? extends T > iterator , Class < T > type ) { } }

implementation: List < T > list = Lists . newArrayList ( iterator ) ; return Iterables . toArray ( list , type ) ;


signature:
public class Iterators { /** * 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 */
public static int frequency ( Iterator < ? > iterator , @ NullableDecl Object element ) { } }

implementation:
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 ;


signature:
public class Iterators { /** * Returns an iterator that cycles indefinitely over the elements of { @ code iterable } .
 * < p > 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 .
 * < p > < b > Warning : < / b > 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 . */
public static < T > Iterator < T > cycle ( final Iterable < T > iterable ) { } }

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


signature:
public class Iterators { /** * 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 . */
private static < T > Iterator < T > consumingForArray ( final T ... elements ) { } }

implementation: 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 ; } } ;


signature:
public class Iterators { /** * 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 . */
public static < T > Iterator < T > concat ( Iterator < ? extends T > a , Iterator < ? extends T > b ) { } }

implementation: checkNotNull ( a ) ; checkNotNull ( b ) ; return concat ( consumingForArray ( a , b ) ) ;


signature:
public class Iterators { /** * 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 */
public static < T > Iterator < T > concat ( Iterator < ? extends T > ... inputs ) { } }

implementation: return concatNoDefensiveCopy ( Arrays . copyOf ( inputs , inputs . length ) ) ;


signature:
public class Iterators { /** * 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 . */
public static < T > Iterator < T > concat ( Iterator < ? extends Iterator < ? extends T > > inputs ) { } }

implementation: return new ConcatenatedIterator < T > ( inputs ) ;


signature:
public class Iterators { /** * Concats a varargs array of iterators without making a defensive copy of the array . */
static < T > Iterator < T > concatNoDefensiveCopy ( Iterator < ? extends T > ... inputs ) { } }

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


signature:
public class Iterators { /** * 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 */
public static < T > UnmodifiableIterator < List < T > > partition ( Iterator < T > iterator , int size ) { } }

implementation: return partitionImpl ( iterator , size , false ) ;


signature:
public class Iterators { /** * 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 */
public static < T > UnmodifiableIterator < List < T > > paddedPartition ( Iterator < T > iterator , int size ) { } }

implementation: return partitionImpl ( iterator , size , true ) ;


signature:
public class Iterators { /** * Returns a view of { @ code unfiltered } containing all elements that are of the type { @ code
 * desiredType } . */
@ 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 ) { } }

implementation: return ( UnmodifiableIterator < T > ) filter ( unfiltered , instanceOf ( desiredType ) ) ;


signature:
public class Iterators { /** * Returns { @ code true } if one or more elements returned by { @ code iterator } satisfy the given
 * predicate . */
public static < T > boolean any ( Iterator < T > iterator , Predicate < ? super T > predicate ) { } }

implementation: return indexOf ( iterator , predicate ) != - 1 ;


signature:
public class Iterators { /** * 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 > boolean all ( Iterator < T > iterator , Predicate < ? super T > predicate ) { } }

implementation: checkNotNull ( predicate ) ; while ( iterator . hasNext ( ) ) { T element = iterator . next ( ) ; if ( ! predicate . apply ( element ) ) { return false ; } } return true ;


signature:
public class Iterators { /** * 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 */
public static < T > T find ( Iterator < T > iterator , Predicate < ? super T > predicate ) { } }

implementation: checkNotNull ( iterator ) ; checkNotNull ( predicate ) ; while ( iterator . hasNext ( ) ) { T t = iterator . next ( ) ; if ( predicate . apply ( t ) ) { return t ; } } throw new NoSuchElementException ( ) ;


signature:
public class Iterators { /** * 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 */
@ NullableDecl public static < T > T find ( Iterator < ? extends T > iterator , Predicate < ? super T > predicate , @ NullableDecl T defaultValue ) { } }

implementation: checkNotNull ( iterator ) ; checkNotNull ( predicate ) ; while ( iterator . hasNext ( ) ) { T t = iterator . next ( ) ; if ( predicate . apply ( t ) ) { return t ; } } return defaultValue ;


signature:
public class Iterators { /** * 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 } .
 * < p > < b > Warning : < / b > 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 */
public static < T > Optional < T > tryFind ( Iterator < T > iterator , Predicate < ? super T > predicate ) { } }

implementation: checkNotNull ( iterator ) ; checkNotNull ( predicate ) ; while ( iterator . hasNext ( ) ) { T t = iterator . next ( ) ; if ( predicate . apply ( t ) ) { return Optional . of ( t ) ; } } return Optional . absent ( ) ;


signature:
public class Iterators { /** * 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 } */
public static < T > T get ( Iterator < T > iterator , int position ) { } }

implementation: 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 ( ) ;


signature:
public class Iterators { /** * 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 */
@ NullableDecl public static < T > T getNext ( Iterator < ? extends T > iterator , @ NullableDecl T defaultValue ) { } }

implementation: return iterator . hasNext ( ) ? iterator . next ( ) : defaultValue ;


signature:
public class Iterators { /** * Advances { @ code iterator } to the end , returning the last element .
 * @ return the last element of { @ code iterator }
 * @ throws NoSuchElementException if the iterator is empty */
public static < T > T getLast ( Iterator < T > iterator ) { } }

implementation: while ( true ) { T current = iterator . next ( ) ; if ( ! iterator . hasNext ( ) ) { return current ; } }


signature:
public class Iterators { /** * 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 */
@ NullableDecl public static < T > T getLast ( Iterator < ? extends T > iterator , @ NullableDecl T defaultValue ) { } }

implementation: return iterator . hasNext ( ) ? getLast ( iterator ) : defaultValue ;


signature:
public class Iterators { /** * 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 */
public static < T > Iterator < T > consumingIterator ( final Iterator < T > iterator ) { } }

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


signature:
public class Iterators { /** * Deletes and returns the next value from the iterator , or returns { @ code null } if there is no
 * such value . */
@ NullableDecl static < T > T pollNext ( Iterator < T > iterator ) { } }

implementation: if ( iterator . hasNext ( ) ) { T result = iterator . next ( ) ; iterator . remove ( ) ; return result ; } else { return null ; }


signature:
public class Iterators { /** * Clears the iterator using its remove method . */
static void clear ( Iterator < ? > iterator ) { } }

implementation: checkNotNull ( iterator ) ; while ( iterator . hasNext ( ) ) { iterator . next ( ) ; iterator . remove ( ) ; }


signature:
public class Iterators { /** * 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 .
 * < p > < b > Note : < / b > It is often preferable to represent your data using a collection type , for
 * example using { @ link Arrays # asList ( Object [ ] ) } , making this method unnecessary .
 * < p > The { @ code Iterable } equivalent of this method is either { @ link Arrays # asList ( Object [ ] ) } ,
 * { @ link ImmutableList # copyOf ( Object [ ] ) } } , or { @ link ImmutableList # of } . */
@ SafeVarargs public static < T > UnmodifiableIterator < T > forArray ( final T ... array ) { } }

implementation: return forArray ( array , 0 , array . length , 0 ) ;


signature:
public class Iterators { /** * 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 ) } . */
static < T > UnmodifiableListIterator < T > forArray ( final T [ ] array , final int offset , int length , int index ) { } }

implementation:
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 ) ;


signature:
public class Iterators { /** * Adapts an { @ code Enumeration } to the { @ code Iterator } interface .
 * < p > This method has no equivalent in { @ link Iterables } because viewing an { @ code Enumeration } as
 * an { @ code Iterable } is impossible . However , the contents can be < i > copied < / i > into a collection
 * using { @ link Collections # list } . */
public static < T > UnmodifiableIterator < T > forEnumeration ( final Enumeration < T > enumeration ) { } }

implementation: checkNotNull ( enumeration ) ; return new UnmodifiableIterator < T > ( ) { @ Override public boolean hasNext ( ) { return enumeration . hasMoreElements ( ) ; } @ Override public T next ( ) { return enumeration . nextElement ( ) ; } } ;


signature:
public class Iterators { /** * 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 ( ) ) } . */
public static < T > Enumeration < T > asEnumeration ( final Iterator < T > iterator ) { } }

implementation: checkNotNull ( iterator ) ; return new Enumeration < T > ( ) { @ Override public boolean hasMoreElements ( ) { return iterator . hasNext ( ) ; } @ Override public T nextElement ( ) { return iterator . next ( ) ; } } ;


signature:
public class Iterators { /** * Returns a { @ code PeekingIterator } backed by the given iterator .
 * < p > 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 :
 * < pre > { @ 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 "
 * } < / pre >
 * < p > 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 .
 * < p > The returned iterator does not support removal after peeking , as explained by { @ link
 * PeekingIterator # remove ( ) } .
 * < p > Note : If the given iterator is already a { @ code PeekingIterator } , it < i > might < / i > be
 * returned to the caller , although this is neither guaranteed to occur nor required to be
 * consistent . For example , this method < i > might < / i > 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 .
 * < p > 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 } . */
public static < T > PeekingIterator < T > peekingIterator ( Iterator < ? extends T > iterator ) { } }

implementation:
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 ) ;


signature:
public class Iterators { /** * Simply returns its argument .
 * @ deprecated no need to use this
 * @ since 10.0 */
@ Deprecated public static < T > PeekingIterator < T > peekingIterator ( PeekingIterator < T > iterator ) { } }

implementation: return checkNotNull ( iterator ) ;


signature:
public class Iterators { /** * 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 .
 * < p > Callers must ensure that the source { @ code iterators } are in non - descending order as this
 * method does not sort its input .
 * < p > For any equivalent elements across all { @ code iterators } , it is undefined which element is
 * returned first .
 * @ since 11.0 */
@ Beta public static < T > UnmodifiableIterator < T > mergeSorted ( Iterable < ? extends Iterator < ? extends T > > iterators , Comparator < ? super T > comparator ) { } }

implementation: checkNotNull ( iterators , "iterators" ) ; checkNotNull ( comparator , "comparator" ) ; return new MergingIterator < T > ( iterators , comparator ) ;


signature:
public class Iterators { /** * Used to avoid http : / / bugs . sun . com / view _ bug . do ? bug _ id = 6558557 */
static < T > ListIterator < T > cast ( Iterator < T > iterator ) { } }

implementation: return ( ListIterator < T > ) iterator ;


signature:
public class ConfigurableMutableNetwork { /** * Adds { @ code node } to the graph and returns the associated { @ link NetworkConnections } .
 * @ throws IllegalStateException if { @ code node } is already present */
@ CanIgnoreReturnValue private NetworkConnections < N , E > addNodeInternal ( N node ) { } }

implementation: NetworkConnections < N , E > connections = newConnections ( ) ; checkState ( nodeConnections . put ( node , connections ) == null ) ; return connections ;


signature:
public class HostSpecifier { /** * 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 .
 * < p > The specifier must be in one of these formats :
 * < ul >
 * < li > A domain name , like { @ code google . com }
 * < li > A IPv4 address string , like { @ code 127.0.0.1}
 * < li > An IPv6 address string with or without brackets , like { @ code [ 2001 : db8 : : 1 ] } or { @ code
 * 2001 : db8 : : 1}
 * < / ul >
 * @ throws IllegalArgumentException if the specifier is not valid . */
public static HostSpecifier fromValid ( String specifier ) { } }

implementation:
// 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 ) ;


signature:
public class HostSpecifier { /** * 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 . */
public static HostSpecifier from ( String specifier ) throws ParseException { } }

implementation:
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 ; }


signature:
public class ByteSink { /** * 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 } ) */
public OutputStream openBufferedStream ( ) throws IOException { } }

implementation: OutputStream out = openStream ( ) ; return ( out instanceof BufferedOutputStream ) ? ( BufferedOutputStream ) out : new BufferedOutputStream ( out ) ;


signature:
public class ByteSink { /** * Writes all the given bytes to this sink .
 * @ throws IOException if an I / O occurs while writing to this sink */
public void write ( byte [ ] bytes ) throws IOException { } }

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


signature:
public class ByteSink { /** * 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 */
@ CanIgnoreReturnValue public long writeFrom ( InputStream input ) throws IOException { } }

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


signature:
public class AbstractMapBasedMultiset { /** * Roughly a 33 % performance improvement over AbstractMultiset . setCount ( ) . */
@ CanIgnoreReturnValue @ Override public int setCount ( @ Nullable E element , int count ) { } }

implementation: 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 ;


signature:
public class Verify { /** * 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 ( ) */
public static void verify ( boolean expression , @ Nullable String errorMessageTemplate , @ Nullable Object @ Nullable . . . errorMessageArgs ) { } }

implementation: if ( ! expression ) { throw new VerifyException ( lenientFormat ( errorMessageTemplate , errorMessageArgs ) ) ; }


signature:
public class Verify { /** * 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) */
public static void verify ( boolean expression , @ Nullable String errorMessageTemplate , char p1 ) { } }

implementation: if ( ! expression ) { throw new VerifyException ( lenientFormat ( errorMessageTemplate , p1 ) ) ; }


signature:
public class Verify { /** * Ensures that { @ code reference } is non - null , throwing a { @ code VerifyException } with a custom
 * message otherwise .
 * @ 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 ) } .
 * @ return { @ code reference } , guaranteed to be non - null , for convenience
 * @ throws VerifyException if { @ code reference } is { @ code null }
 * @ see Preconditions # checkNotNull Preconditions . checkNotNull ( ) */
@ CanIgnoreReturnValue public static < T > T verifyNotNull ( @ Nullable T reference , @ Nullable String errorMessageTemplate , @ Nullable Object @ Nullable . . . errorMessageArgs ) { } }

implementation: verify ( reference != null , errorMessageTemplate , errorMessageArgs ) ; return reference ;


signature:
public class Queues { /** * Creates an { @ code ArrayDeque } containing the elements of the specified iterable , in the order
 * they are returned by the iterable ' s iterator .
 * @ since 12.0 */
public static < E > ArrayDeque < E > newArrayDeque ( Iterable < ? extends E > elements ) { } }

implementation: if ( elements instanceof Collection ) { return new ArrayDeque < E > ( Collections2 . cast ( elements ) ) ; } ArrayDeque < E > deque = new ArrayDeque < E > ( ) ; Iterables . addAll ( deque , elements ) ; return deque ;


signature:
public class Queues { /** * Creates a { @ code ConcurrentLinkedQueue } containing the elements of the specified iterable , in
 * the order they are returned by the iterable ' s iterator . */
@ GwtIncompatible // ConcurrentLinkedQueue
public static < E > ConcurrentLinkedQueue < E > newConcurrentLinkedQueue ( Iterable < ? extends E > elements ) { } }

implementation: if ( elements instanceof Collection ) { return new ConcurrentLinkedQueue < E > ( Collections2 . cast ( elements ) ) ; } ConcurrentLinkedQueue < E > queue = new ConcurrentLinkedQueue < E > ( ) ; Iterables . addAll ( queue , elements ) ; return queue ;


signature:
public class Queues { /** * Creates a { @ code LinkedBlockingQueue } with a capacity of { @ link Integer # MAX _ VALUE } , containing
 * the elements of the specified iterable , in the order they are returned by the iterable ' s
 * iterator .
 * @ param elements the elements that the queue should contain , in order
 * @ return a new { @ code LinkedBlockingQueue } containing those elements */
@ GwtIncompatible // LinkedBlockingQueue
public static < E > LinkedBlockingQueue < E > newLinkedBlockingQueue ( Iterable < ? extends E > elements ) { } }

implementation: if ( elements instanceof Collection ) { return new LinkedBlockingQueue < E > ( Collections2 . cast ( elements ) ) ; } LinkedBlockingQueue < E > queue = new LinkedBlockingQueue < E > ( ) ; Iterables . addAll ( queue , elements ) ; return queue ;


signature:
public class Queues { /** * Creates a { @ code PriorityQueue } containing the given elements .
 * < p > < b > Note : < / b > If the specified iterable is a { @ code SortedSet } or a { @ code PriorityQueue } ,
 * this priority queue will be ordered according to the same ordering .
 * @ since 11.0 ( requires that { @ code E } be { @ code Comparable } since 15.0 ) . */
public static < E extends Comparable > PriorityQueue < E > newPriorityQueue ( Iterable < ? extends E > elements ) { } }

implementation: if ( elements instanceof Collection ) { return new PriorityQueue < E > ( Collections2 . cast ( elements ) ) ; } PriorityQueue < E > queue = new PriorityQueue < E > ( ) ; Iterables . addAll ( queue , elements ) ; return queue ;


signature:
public class Queues { /** * Drains the queue as { @ linkplain # drain ( BlockingQueue , Collection , int , long , TimeUnit ) } , but
 * with a different behavior in case it is interrupted while waiting . In that case , the operation
 * will continue as usual , and in the end the thread ' s interruption status will be set ( no { @ code
 * InterruptedException } is thrown ) .
 * @ param q the blocking queue to be drained
 * @ param buffer where to add the transferred elements
 * @ param numElements the number of elements to be waited for
 * @ param timeout how long to wait before giving up , in units of { @ code unit }
 * @ param unit a { @ code TimeUnit } determining how to interpret the timeout parameter
 * @ return the number of elements transferred */
@ Beta @ CanIgnoreReturnValue @ GwtIncompatible // BlockingQueue
@ SuppressWarnings ( "GoodTime" ) // should accept a java . time . Duration
public static < E > int drainUninterruptibly ( BlockingQueue < E > q , Collection < ? super E > buffer , int numElements , long timeout , TimeUnit unit ) { } }

implementation:
Preconditions . checkNotNull ( buffer ) ; long deadline = System . nanoTime ( ) + unit . toNanos ( timeout ) ; int added = 0 ; boolean interrupted = false ; try { while ( added < numElements ) { // we could rely solely on # poll , but # drainTo might be more efficient when there are
// multiple elements already available ( e . g . LinkedBlockingQueue # drainTo locks only once )
added += q . drainTo ( buffer , numElements - added ) ; if ( added < numElements ) { // not enough elements immediately available ; will have to poll
E e ; // written exactly once , by a successful ( uninterrupted ) invocation of # poll
while ( true ) { try { e = q . poll ( deadline - System . nanoTime ( ) , TimeUnit . NANOSECONDS ) ; break ; } catch ( InterruptedException ex ) { interrupted = true ; // note interruption and retry
} } if ( e == null ) { break ; // we already waited enough , and there are no more elements in sight
} buffer . add ( e ) ; added ++ ; } } } finally { if ( interrupted ) { Thread . currentThread ( ) . interrupt ( ) ; } } return added ;


signature:
public class Queues { /** * Returns a synchronized ( thread - safe ) queue backed by the specified queue . In order to guarantee
 * serial access , it is critical that < b > all < / b > access to the backing queue is accomplished
 * through the returned queue .
 * < p > It is imperative that the user manually synchronize on the returned queue when accessing the
 * queue ' s iterator :
 * < pre > { @ code
 * Queue < E > queue = Queues . synchronizedQueue ( MinMaxPriorityQueue . < E > create ( ) ) ;
 * queue . add ( element ) ; / / Needn ' t be in synchronized block
 * synchronized ( queue ) { / / Must synchronize on queue !
 * Iterator < E > i = queue . iterator ( ) ; / / Must be in synchronized block
 * while ( i . hasNext ( ) ) {
 * foo ( i . next ( ) ) ;
 * } < / pre >
 * < p > Failure to follow this advice may result in non - deterministic behavior .
 * < p > The returned queue will be serializable if the specified queue is serializable .
 * @ param queue the queue to be wrapped in a synchronized view
 * @ return a synchronized view of the specified queue
 * @ since 14.0 */
public static < E > Queue < E > synchronizedQueue ( Queue < E > queue ) { } }

implementation: return Synchronized . queue ( queue , null ) ;


signature:
public class Queues { /** * Returns a synchronized ( thread - safe ) deque backed by the specified deque . In order to guarantee
 * serial access , it is critical that < b > all < / b > access to the backing deque is accomplished
 * through the returned deque .
 * < p > It is imperative that the user manually synchronize on the returned deque when accessing any
 * of the deque ' s iterators :
 * < pre > { @ code
 * Deque < E > deque = Queues . synchronizedDeque ( Queues . < E > newArrayDeque ( ) ) ;
 * deque . add ( element ) ; / / Needn ' t be in synchronized block
 * synchronized ( deque ) { / / Must synchronize on deque !
 * Iterator < E > i = deque . iterator ( ) ; / / Must be in synchronized block
 * while ( i . hasNext ( ) ) {
 * foo ( i . next ( ) ) ;
 * } < / pre >
 * < p > Failure to follow this advice may result in non - deterministic behavior .
 * < p > The returned deque will be serializable if the specified deque is serializable .
 * @ param deque the deque to be wrapped in a synchronized view
 * @ return a synchronized view of the specified deque
 * @ since 15.0 */
public static < E > Deque < E > synchronizedDeque ( Deque < E > deque ) { } }

implementation: return Synchronized . deque ( deque , null ) ;


signature:
public class StandardTable { /** * Remove a row key / column key / value mapping , if present . */
private boolean removeMapping ( Object rowKey , Object columnKey , Object value ) { } }

implementation: if ( containsMapping ( rowKey , columnKey , value ) ) { remove ( rowKey , columnKey ) ; return true ; } return false ;


signature:
public class StandardTable { /** * { @ inheritDoc }
 * < p > The returned set has an iterator that does not support { @ code remove ( ) } .
 * < p > The set ' s iterator traverses the columns of the first row , the columns of the second row ,
 * etc . , skipping any columns that have appeared previously . */
@ Override public Set < C > columnKeySet ( ) { } }

implementation: Set < C > result = columnKeySet ; return ( result == null ) ? columnKeySet = new ColumnKeySet ( ) : result ;


signature:
public class CacheBuilderSpec { /** * Creates a CacheBuilderSpec from a string .
 * @ param cacheBuilderSpecification the string form */
public static CacheBuilderSpec parse ( String cacheBuilderSpecification ) { } }

implementation:
CacheBuilderSpec spec = new CacheBuilderSpec ( cacheBuilderSpecification ) ; if ( ! cacheBuilderSpecification . isEmpty ( ) ) { for ( String keyValuePair : KEYS_SPLITTER . split ( cacheBuilderSpecification ) ) { List < String > keyAndValue = ImmutableList . copyOf ( KEY_VALUE_SPLITTER . split ( keyValuePair ) ) ; checkArgument ( ! keyAndValue . isEmpty ( ) , "blank key-value pair" ) ; checkArgument ( keyAndValue . size ( ) <= 2 , "key-value pair %s with more than one equals sign" , keyValuePair ) ; // Find the ValueParser for the current key .
String key = keyAndValue . get ( 0 ) ; ValueParser valueParser = VALUE_PARSERS . get ( key ) ; checkArgument ( valueParser != null , "unknown key %s" , key ) ; String value = keyAndValue . size ( ) == 1 ? null : keyAndValue . get ( 1 ) ; valueParser . parse ( spec , key , value ) ; } } return spec ;


signature:
public class CacheBuilderSpec { /** * Returns a CacheBuilder configured according to this instance ' s specification . */
CacheBuilder < Object , Object > toCacheBuilder ( ) { } }

implementation: CacheBuilder < Object , Object > builder = CacheBuilder . newBuilder ( ) ; if ( initialCapacity != null ) { builder . initialCapacity ( initialCapacity ) ; } if ( maximumSize != null ) { builder . maximumSize ( maximumSize ) ; } if ( maximumWeight != null ) { builder . maximumWeight ( maximumWeight ) ; } if ( concurrencyLevel != null ) { builder . concurrencyLevel ( concurrencyLevel ) ; } if ( keyStrength != null ) { switch ( keyStrength ) { case WEAK : builder . weakKeys ( ) ; break ; default : throw new AssertionError ( ) ; } } if ( valueStrength != null ) { switch ( valueStrength ) { case SOFT : builder . softValues ( ) ; break ; case WEAK : builder . weakValues ( ) ; break ; default : throw new AssertionError ( ) ; } } if ( recordStats != null && recordStats ) { builder . recordStats ( ) ; } if ( writeExpirationTimeUnit != null ) { builder . expireAfterWrite ( writeExpirationDuration , writeExpirationTimeUnit ) ; } if ( accessExpirationTimeUnit != null ) { builder . expireAfterAccess ( accessExpirationDuration , accessExpirationTimeUnit ) ; } if ( refreshTimeUnit != null ) { builder . refreshAfterWrite ( refreshDuration , refreshTimeUnit ) ; } return builder ;


signature:
public class CacheBuilderSpec { /** * Converts an expiration duration / unit pair into a single Long for hashing and equality . Uses
 * nanos to match CacheBuilder implementation . */
@ NullableDecl private static Long durationInNanos ( long duration , @ NullableDecl TimeUnit unit ) { } }

implementation: return ( unit == null ) ? null : unit . toNanos ( duration ) ;


signature:
public class EnumBiMap { /** * Returns a new , empty { @ code EnumBiMap } using the specified key and value types .
 * @ param keyType the key type
 * @ param valueType the value type */
public static < K extends Enum < K > , V extends Enum < V > > EnumBiMap < K , V > create ( Class < K > keyType , Class < V > valueType ) { } }

implementation: return new EnumBiMap < > ( keyType , valueType ) ;


signature:
public class Comparators { /** * Returns { @ code true } if each element in { @ code iterable } after the first is greater than or
 * equal to the element that preceded it , according to the specified comparator . Note that this is
 * always true when the iterable has fewer than two elements . */
@ Beta public static < T > boolean isInOrder ( Iterable < ? extends T > iterable , Comparator < T > comparator ) { } }

implementation: checkNotNull ( comparator ) ; Iterator < ? extends T > it = iterable . iterator ( ) ; if ( it . hasNext ( ) ) { T prev = it . next ( ) ; while ( it . hasNext ( ) ) { T next = it . next ( ) ; if ( comparator . compare ( prev , next ) > 0 ) { return false ; } prev = next ; } } return true ;


signature:
public class Comparators { /** * Returns a { @ code Collector } that returns the { @ code k } smallest ( relative to the specified
 * { @ code Comparator } ) input elements , in ascending order , as an unmodifiable { @ code List } . Ties
 * are broken arbitrarily .
 * < p > For example :
 * < pre > { @ code
 * Stream . of ( " foo " , " quux " , " banana " , " elephant " )
 * . collect ( least ( 2 , comparingInt ( String : : length ) ) )
 * / / returns { " foo " , " quux " }
 * } < / pre >
 * < p > This { @ code Collector } uses O ( k ) memory and takes expected time O ( n ) ( worst - case O ( n log
 * k ) ) , as opposed to e . g . { @ code Stream . sorted ( comparator ) . limit ( k ) } , which currently takes O ( n
 * log n ) time and O ( n ) space .
 * @ throws IllegalArgumentException if { @ code k < 0}
 * @ since 22.0 */
public static < T > Collector < T , ? , List < T > > least ( int k , Comparator < ? super T > comparator ) { } }

implementation: checkNonnegative ( k , "k" ) ; checkNotNull ( comparator ) ; return Collector . of ( ( ) -> TopKSelector . < T > least ( k , comparator ) , TopKSelector :: offer , TopKSelector :: combine , TopKSelector :: topK , Collector . Characteristics . UNORDERED ) ;


signature:
public class Comparators { /** * Returns a comparator of { @ link Optional } values which treats { @ link Optional # empty } as less
 * than all other values , and orders the rest using { @ code valueComparator } on the contained
 * value .
 * @ since 22.0 */
@ Beta public static < T > Comparator < Optional < T > > emptiesFirst ( Comparator < ? super T > valueComparator ) { } }

implementation: checkNotNull ( valueComparator ) ; return Comparator . comparing ( o -> o . orElse ( null ) , Comparator . nullsFirst ( valueComparator ) ) ;


signature:
public class Comparators { /** * Returns a comparator of { @ link Optional } values which treats { @ link Optional # empty } as greater
 * than all other values , and orders the rest using { @ code valueComparator } on the contained
 * value .
 * @ since 22.0 */
@ Beta public static < T > Comparator < Optional < T > > emptiesLast ( Comparator < ? super T > valueComparator ) { } }

implementation: checkNotNull ( valueComparator ) ; return Comparator . comparing ( o -> o . orElse ( null ) , Comparator . nullsLast ( valueComparator ) ) ;


signature:
public class CharSource { /** * Opens a new { @ link Stream } for reading text one line at a time from this source . This method
 * returns a new , independent stream each time it is called .
 * < p > The returned stream is lazy and only reads from the source in the terminal operation . If an
 * I / O error occurs while the stream is reading from the source or when the stream is closed , an
 * { @ link UncheckedIOException } is thrown .
 * < 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 .
 * < p > The caller is responsible for ensuring that the returned stream is closed . For example :
 * < pre > { @ code
 * try ( Stream < String > lines = source . lines ( ) ) {
 * lines . map ( . . . )
 * . filter ( . . . )
 * . forEach ( . . . ) ;
 * } < / pre >
 * @ throws IOException if an I / O error occurs while opening the stream
 * @ since 22.0 */
@ Beta @ MustBeClosed public Stream < String > lines ( ) throws IOException { } }

implementation: BufferedReader reader = openBufferedStream ( ) ; return reader . lines ( ) . onClose ( ( ) -> { try { reader . close ( ) ; } catch ( IOException e ) { throw new UncheckedIOException ( e ) ; } } ) ;


signature:
public class CharSource { /** * Reads all lines of text from this source , running the given { @ code action } for each line as it
 * is read .
 * < 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 or if { @ code action }
 * throws an { @ code UncheckedIOException }
 * @ since 22.0 */
@ Beta public void forEachLine ( Consumer < ? super String > action ) throws IOException { } }

implementation:
try ( Stream < String > lines = lines ( ) ) { // The lines should be ordered regardless in most cases , but use forEachOrdered to be sure
lines . forEachOrdered ( action ) ; } catch ( UncheckedIOException e ) { throw e . getCause ( ) ; }


signature:
public class Optional { /** * If { @ code nullableReference } is non - null , returns an { @ code Optional } instance containing that
 * reference ; otherwise returns { @ link Optional # absent } .
 * < p > < b > Comparison to { @ code java . util . Optional } : < / b > this method is equivalent to Java 8 ' s
 * { @ code Optional . ofNullable } . */
public static < T > Optional < T > fromNullable ( @ Nullable T nullableReference ) { } }

implementation: return ( nullableReference == null ) ? Optional . < T > absent ( ) : new Present < T > ( nullableReference ) ;


signature:
public class Optional { /** * Returns the equivalent { @ code com . google . common . base . Optional } value to the given { @ code
 * java . util . Optional } , or { @ code null } if the argument is null .
 * @ since 21.0 */
public static < T > @ Nullable Optional < T > fromJavaUtil ( java . util . @ Nullable Optional < T > javaUtilOptional ) { } }

implementation: return ( javaUtilOptional == null ) ? null : fromNullable ( javaUtilOptional . orElse ( null ) ) ;


signature:
public class Optional { /** * Returns the equivalent { @ code java . util . Optional } value to the given { @ code
 * com . google . common . base . Optional } , or { @ code null } if the argument is null .
 * < p > If { @ code googleOptional } is known to be non - null , use { @ code googleOptional . toJavaUtil ( ) }
 * instead .
 * < p > Unfortunately , the method reference { @ code Optional : : toJavaUtil } will not work , because it
 * could refer to either the static or instance version of this method . Write out the lambda
 * expression { @ code o - > Optional . toJavaUtil ( o ) } instead .
 * @ since 21.0 */
public static < T > java . util . @ Nullable Optional < T > toJavaUtil ( @ Nullable Optional < T > googleOptional ) { } }

implementation: return googleOptional == null ? null : googleOptional . toJavaUtil ( ) ;


signature:
public class Optional { /** * Returns the equivalent { @ code java . util . Optional } value to this optional .
 * < p > Unfortunately , the method reference { @ code Optional : : toJavaUtil } will not work , because it
 * could refer to either the static or instance version of this method . Write out the lambda
 * expression { @ code o - > o . toJavaUtil ( ) } instead .
 * @ since 21.0 */
public java . util . Optional < T > toJavaUtil ( ) { } }

implementation: return java . util . Optional . ofNullable ( orNull ( ) ) ;


signature:
public class Optional { /** * Returns the value of each present instance from the supplied { @ code optionals } , in order ,
 * skipping over occurrences of { @ link Optional # absent } . Iterators are unmodifiable and are
 * evaluated lazily .
 * < p > < b > Comparison to { @ code java . util . Optional } : < / b > this method has no equivalent in Java 8 ' s
 * { @ code Optional } class ; use { @ code
 * optionals . stream ( ) . filter ( Optional : : isPresent ) . map ( Optional : : get ) } instead .
 * @ since 11.0 ( generics widened in 13.0) */
@ Beta public static < T > Iterable < T > presentInstances ( final Iterable < ? extends Optional < ? extends T > > optionals ) { } }

implementation: checkNotNull ( optionals ) ; return new Iterable < T > ( ) { @ Override public Iterator < T > iterator ( ) { return new AbstractIterator < T > ( ) { private final Iterator < ? extends Optional < ? extends T > > iterator = checkNotNull ( optionals . iterator ( ) ) ; @ Override protected T computeNext ( ) { while ( iterator . hasNext ( ) ) { Optional < ? extends T > optional = iterator . next ( ) ; if ( optional . isPresent ( ) ) { return optional . get ( ) ; } } return endOfData ( ) ; } } ; } } ;


signature:
public class ImmutableSetMultimap { /** * Casting is safe because the multimap will never hold any elements . */
@ SuppressWarnings ( "unchecked" ) public static < K , V > ImmutableSetMultimap < K , V > of ( ) { } }

implementation: return ( ImmutableSetMultimap < K , V > ) EmptyImmutableSetMultimap . INSTANCE ;


signature:
public class ImmutableSetMultimap { /** * Returns an immutable set multimap containing the same mappings as { @ code multimap } . The
 * generated multimap ' s key and value orderings correspond to the iteration ordering of the { @ code
 * multimap . asMap ( ) } view . Repeated occurrences of an entry in the multimap after the first are
 * ignored .
 * < p > Despite the method name , this method attempts to avoid actually copying the data when it is
 * safe to do so . The exact circumstances under which a copy will or will not be performed are
 * undocumented and subject to change .
 * @ throws NullPointerException if any key or value in { @ code multimap } is null */
public static < K , V > ImmutableSetMultimap < K , V > copyOf ( Multimap < ? extends K , ? extends V > multimap ) { } }

implementation: return copyOf ( multimap , null ) ;


signature:
public class ImmutableSetMultimap { /** * { @ inheritDoc }
 * < p > Because an inverse of a set multimap cannot contain multiple pairs with the same key and
 * value , this method returns an { @ code ImmutableSetMultimap } rather than the { @ code
 * ImmutableMultimap } specified in the { @ code ImmutableMultimap } class . */
@ Override public ImmutableSetMultimap < V , K > inverse ( ) { } }

implementation: ImmutableSetMultimap < V , K > result = inverse ; return ( result == null ) ? ( inverse = invert ( ) ) : result ;


signature:
public class Joiner { /** * Appends the string representation of each of { @ code parts } , using the previously configured
 * separator between each , to { @ code appendable } .
 * @ since 11.0 */
@ CanIgnoreReturnValue public < A extends Appendable > A appendTo ( A appendable , Iterator < ? > parts ) throws IOException { } }

implementation: checkNotNull ( appendable ) ; if ( parts . hasNext ( ) ) { appendable . append ( toString ( parts . next ( ) ) ) ; while ( parts . hasNext ( ) ) { appendable . append ( separator ) ; appendable . append ( toString ( parts . next ( ) ) ) ; } } return appendable ;