signature:
public class Multisets { /** * An implementation of { @ link Multiset # addAll } . */
static < E > boolean addAllImpl ( Multiset < E > self , Collection < ? extends E > elements ) { } }

implementation: checkNotNull ( self ) ; checkNotNull ( elements ) ; if ( elements instanceof Multiset ) { return addAllImpl ( self , cast ( elements ) ) ; } else if ( elements . isEmpty ( ) ) { return false ; } else { return Iterators . addAll ( self , elements . iterator ( ) ) ; }


signature:
public class Multisets { /** * A specialization of { @ code addAllImpl } for when { @ code elements } is itself a Multiset . */
private static < E > boolean addAllImpl ( Multiset < E > self , Multiset < ? extends E > elements ) { } }

implementation: if ( elements . isEmpty ( ) ) { return false ; } elements . forEachEntry ( self :: add ) ; return true ;


signature:
public class Multisets { /** * An implementation of { @ link Multiset # removeAll } . */
static boolean removeAllImpl ( Multiset < ? > self , Collection < ? > elementsToRemove ) { } }

implementation: Collection < ? > collection = ( elementsToRemove instanceof Multiset ) ? ( ( Multiset < ? > ) elementsToRemove ) . elementSet ( ) : elementsToRemove ; return self . elementSet ( ) . removeAll ( collection ) ;


signature:
public class Multisets { /** * An implementation of { @ link Multiset # retainAll } . */
static boolean retainAllImpl ( Multiset < ? > self , Collection < ? > elementsToRetain ) { } }

implementation: checkNotNull ( elementsToRetain ) ; Collection < ? > collection = ( elementsToRetain instanceof Multiset ) ? ( ( Multiset < ? > ) elementsToRetain ) . elementSet ( ) : elementsToRetain ; return self . elementSet ( ) . retainAll ( collection ) ;


signature:
public class Multisets { /** * An implementation of { @ link Multiset # setCount ( Object , int ) } . */
static < E > int setCountImpl ( Multiset < E > self , E element , int count ) { } }

implementation: checkNonnegative ( count , "count" ) ; int oldCount = self . count ( element ) ; int delta = count - oldCount ; if ( delta > 0 ) { self . add ( element , delta ) ; } else if ( delta < 0 ) { self . remove ( element , - delta ) ; } return oldCount ;


signature:
public class Multisets { /** * An implementation of { @ link Multiset # setCount ( Object , int , int ) } . */
static < E > boolean setCountImpl ( Multiset < E > self , E element , int oldCount , int newCount ) { } }

implementation: checkNonnegative ( oldCount , "oldCount" ) ; checkNonnegative ( newCount , "newCount" ) ; if ( self . count ( element ) == oldCount ) { self . setCount ( element , newCount ) ; return true ; } else { return false ; }


signature:
public class Multisets { /** * An implementation of { @ link Multiset # iterator } . */
static < E > Iterator < E > iteratorImpl ( Multiset < E > multiset ) { } }

implementation: return new MultisetIteratorImpl < E > ( multiset , multiset . entrySet ( ) . iterator ( ) ) ;


signature:
public class Multisets { /** * Used to avoid http : / / bugs . sun . com / view _ bug . do ? bug _ id = 6558557 */
static < T > Multiset < T > cast ( Iterable < T > iterable ) { } }

implementation: return ( Multiset < T > ) iterable ;


signature:
public class Multisets { /** * Returns a copy of { @ code multiset } as an { @ link ImmutableMultiset } whose iteration order is
 * highest count first , with ties broken by the iteration order of the original multiset .
 * @ since 11.0 */
@ Beta public static < E > ImmutableMultiset < E > copyHighestCountFirst ( Multiset < E > multiset ) { } }

implementation: Entry < E > [ ] entries = ( Entry < E > [ ] ) multiset . entrySet ( ) . toArray ( new Entry [ 0 ] ) ; Arrays . sort ( entries , DecreasingCount . INSTANCE ) ; return ImmutableMultiset . copyFromEntries ( Arrays . asList ( entries ) ) ;


signature:
public class AbstractInvocationHandler { /** * { @ inheritDoc }
 * < ul >
 * < li > { @ code proxy . hashCode ( ) } delegates to { @ link AbstractInvocationHandler # hashCode }
 * < li > { @ code proxy . toString ( ) } delegates to { @ link AbstractInvocationHandler # toString }
 * < li > { @ code proxy . equals ( argument ) } returns true if :
 * < ul >
 * < li > { @ code proxy } and { @ code argument } are of the same type
 * < li > and { @ link AbstractInvocationHandler # equals } returns true for the { @ link
 * InvocationHandler } of { @ code argument }
 * < / ul >
 * < li > other method calls are dispatched to { @ link # handleInvocation } .
 * < / ul > */
@ Override public final Object invoke ( Object proxy , Method method , Object @ Nullable [ ] args ) throws Throwable { } }

implementation: if ( args == null ) { args = NO_ARGS ; } if ( args . length == 0 && method . getName ( ) . equals ( "hashCode" ) ) { return hashCode ( ) ; } if ( args . length == 1 && method . getName ( ) . equals ( "equals" ) && method . getParameterTypes ( ) [ 0 ] == Object . class ) { Object arg = args [ 0 ] ; if ( arg == null ) { return false ; } if ( proxy == arg ) { return true ; } return isProxyOfSameInterfaces ( arg , proxy . getClass ( ) ) && equals ( Proxy . getInvocationHandler ( arg ) ) ; } if ( args . length == 0 && method . getName ( ) . equals ( "toString" ) ) { return toString ( ) ; } return handleInvocation ( proxy , method , args ) ;


signature:
public class CharMatcher { /** * Returns a { @ code char } matcher that matches any BMP character present in the given character
 * sequence . Returns a bogus matcher if the sequence contains supplementary characters . */
public static CharMatcher anyOf ( final CharSequence sequence ) { } }

implementation:
switch ( sequence . length ( ) ) { case 0 : return none ( ) ; case 1 : return is ( sequence . charAt ( 0 ) ) ; case 2 : return isEither ( sequence . charAt ( 0 ) , sequence . charAt ( 1 ) ) ; default : // TODO ( lowasser ) : is it potentially worth just going ahead and building a precomputed
// matcher ?
return new AnyOf ( sequence ) ; }


signature:
public class CharMatcher { /** * Returns a matcher with identical behavior to the given { @ link Character } - based predicate , but
 * which operates on primitive { @ code char } instances instead . */
public static CharMatcher forPredicate ( final Predicate < ? super Character > predicate ) { } }

implementation: return predicate instanceof CharMatcher ? ( CharMatcher ) predicate : new ForPredicate ( predicate ) ;


signature:
public class CharMatcher { /** * This is the actual implementation of { @ link # precomputed } , but we bounce calls through a method
 * on { @ link Platform } so that we can have different behavior in GWT .
 * < p > This implementation tries to be smart in a number of ways . It recognizes cases where the
 * negation is cheaper to precompute than the matcher itself ; it tries to build small hash tables
 * for matchers that only match a few characters , and so on . In the worst - case scenario , it
 * constructs an eight - kilobyte bit array and queries that . In many situations this produces a
 * matcher which is faster to query than the original . */
@ GwtIncompatible // SmallCharMatcher
CharMatcher precomputedInternal ( ) { } }

implementation:
final BitSet table = new BitSet ( ) ; setBits ( table ) ; int totalCharacters = table . cardinality ( ) ; if ( totalCharacters * 2 <= DISTINCT_CHARS ) { return precomputedPositive ( totalCharacters , table , toString ( ) ) ; } else { // TODO ( lowasser ) : is it worth it to worry about the last character of large matchers ?
table . flip ( Character . MIN_VALUE , Character . MAX_VALUE + 1 ) ; int negatedCharacters = DISTINCT_CHARS - totalCharacters ; String suffix = ".negate()" ; final String description = toString ( ) ; String negatedDescription = description . endsWith ( suffix ) ? description . substring ( 0 , description . length ( ) - suffix . length ( ) ) : description + suffix ; return new NegatedFastMatcher ( precomputedPositive ( negatedCharacters , table , negatedDescription ) ) { @ Override public String toString ( ) { return description ; } } ; }


signature:
public class CharMatcher { /** * Helper method for { @ link # precomputedInternal } that doesn ' t test if the negation is cheaper . */
@ GwtIncompatible // SmallCharMatcher
private static CharMatcher precomputedPositive ( int totalCharacters , BitSet table , String description ) { } }

implementation: switch ( totalCharacters ) { case 0 : return none ( ) ; case 1 : return is ( ( char ) table . nextSetBit ( 0 ) ) ; case 2 : char c1 = ( char ) table . nextSetBit ( 0 ) ; char c2 = ( char ) table . nextSetBit ( c1 + 1 ) ; return isEither ( c1 , c2 ) ; default : return isSmall ( totalCharacters , table . length ( ) ) ? SmallCharMatcher . from ( table , description ) : new BitSetMatcher ( table , description ) ; }


signature:
public class CharMatcher { /** * Returns { @ code true } if a character sequence contains only matching BMP characters .
 * < p > The default implementation iterates over the sequence , invoking { @ link # matches } for each
 * character , until this returns { @ code false } or the end is reached .
 * @ param sequence the character sequence to examine , possibly empty
 * @ return { @ code true } if this matcher matches every character in the sequence , including when
 * the sequence is empty */
public boolean matchesAllOf ( CharSequence sequence ) { } }

implementation: for ( int i = sequence . length ( ) - 1 ; i >= 0 ; i -- ) { if ( ! matches ( sequence . charAt ( i ) ) ) { return false ; } } return true ;


signature:
public class CharMatcher { /** * Returns the index of the first matching BMP character in a character sequence , starting from a
 * given position , or { @ code - 1 } if no character matches after that position .
 * < p > The default implementation iterates over the sequence in forward order , beginning at { @ code
 * start } , calling { @ link # matches } for each character .
 * @ param sequence the character sequence to examine
 * @ param start the first index to examine ; must be nonnegative and no greater than { @ code
 * sequence . length ( ) }
 * @ return the index of the first matching character , guaranteed to be no less than { @ code start } ,
 * or { @ code - 1 } if no character matches
 * @ throws IndexOutOfBoundsException if start is negative or greater than { @ code
 * sequence . length ( ) } */
public int indexIn ( CharSequence sequence , int start ) { } }

implementation: int length = sequence . length ( ) ; checkPositionIndex ( start , length ) ; for ( int i = start ; i < length ; i ++ ) { if ( matches ( sequence . charAt ( i ) ) ) { return i ; } } return - 1 ;


signature:
public class CharMatcher { /** * Returns the index of the last matching BMP character in a character sequence , or { @ code - 1 } if
 * no matching character is present .
 * < p > The default implementation iterates over the sequence in reverse order calling { @ link
 * # matches } for each character .
 * @ param sequence the character sequence to examine from the end
 * @ return an index , or { @ code - 1 } if no character matches */
public int lastIndexIn ( CharSequence sequence ) { } }

implementation: for ( int i = sequence . length ( ) - 1 ; i >= 0 ; i -- ) { if ( matches ( sequence . charAt ( i ) ) ) { return i ; } } return - 1 ;


signature:
public class CharMatcher { /** * Returns the number of matching { @ code char } s found in a character sequence .
 * < p > Counts 2 per supplementary character , such as for { @ link # whitespace } ( ) . { @ link # negate } ( ) . */
public int countIn ( CharSequence sequence ) { } }

implementation: int count = 0 ; for ( int i = 0 ; i < sequence . length ( ) ; i ++ ) { if ( matches ( sequence . charAt ( i ) ) ) { count ++ ; } } return count ;


signature:
public class CharMatcher { /** * Returns a string containing all non - matching characters of a character sequence , in order . For
 * example :
 * < pre > { @ code
 * CharMatcher . is ( ' a ' ) . removeFrom ( " bazaar " )
 * } < / pre >
 * . . . returns { @ code " bzr " } . */
public String removeFrom ( CharSequence sequence ) { } }

implementation:
String string = sequence . toString ( ) ; int pos = indexIn ( string ) ; if ( pos == - 1 ) { return string ; } char [ ] chars = string . toCharArray ( ) ; int spread = 1 ; // This unusual loop comes from extensive benchmarking
OUT : while ( true ) { pos ++ ; while ( true ) { if ( pos == chars . length ) { break OUT ; } if ( matches ( chars [ pos ] ) ) { break ; } chars [ pos - spread ] = chars [ pos ] ; pos ++ ; } spread ++ ; } return new String ( chars , 0 , pos - spread ) ;


signature:
public class CharMatcher { /** * Returns a substring of the input character sequence that omits all matching BMP characters from
 * the beginning and from the end of the string . For example :
 * < pre > { @ code
 * CharMatcher . anyOf ( " ab " ) . trimFrom ( " abacatbab " )
 * } < / pre >
 * . . . returns { @ code " cat " } .
 * < p > Note that :
 * < pre > { @ code
 * CharMatcher . inRange ( ' \ 0 ' , ' ' ) . trimFrom ( str )
 * } < / pre >
 * . . . is equivalent to { @ link String # trim ( ) } . */
public String trimFrom ( CharSequence sequence ) { } }

implementation: int len = sequence . length ( ) ; int first ; int last ; for ( first = 0 ; first < len ; first ++ ) { if ( ! matches ( sequence . charAt ( first ) ) ) { break ; } } for ( last = len - 1 ; last > first ; last -- ) { if ( ! matches ( sequence . charAt ( last ) ) ) { break ; } } return sequence . subSequence ( first , last + 1 ) . toString ( ) ;


signature:
public class CharMatcher { /** * Returns a substring of the input character sequence that omits all matching BMP characters from
 * the beginning of the string . For example :
 * < pre > { @ code
 * CharMatcher . anyOf ( " ab " ) . trimLeadingFrom ( " abacatbab " )
 * } < / pre >
 * . . . returns { @ code " catbab " } . */
public String trimLeadingFrom ( CharSequence sequence ) { } }

implementation: int len = sequence . length ( ) ; for ( int first = 0 ; first < len ; first ++ ) { if ( ! matches ( sequence . charAt ( first ) ) ) { return sequence . subSequence ( first , len ) . toString ( ) ; } } return "" ;


signature:
public class CharMatcher { /** * Returns a substring of the input character sequence that omits all matching BMP characters from
 * the end of the string . For example :
 * < pre > { @ code
 * CharMatcher . anyOf ( " ab " ) . trimTrailingFrom ( " abacatbab " )
 * } < / pre >
 * . . . returns { @ code " abacat " } . */
public String trimTrailingFrom ( CharSequence sequence ) { } }

implementation: int len = sequence . length ( ) ; for ( int last = len - 1 ; last >= 0 ; last -- ) { if ( ! matches ( sequence . charAt ( last ) ) ) { return sequence . subSequence ( 0 , last + 1 ) . toString ( ) ; } } return "" ;


signature:
public class HashBasedTable { /** * Creates an empty { @ code HashBasedTable } . */
public static < R , C , V > HashBasedTable < R , C , V > create ( ) { } }

implementation: return new HashBasedTable < > ( new LinkedHashMap < R , Map < C , V > > ( ) , new Factory < C , V > ( 0 ) ) ;


signature:
public class HashBasedTable { /** * Creates an empty { @ code HashBasedTable } with the specified map sizes .
 * @ param expectedRows the expected number of distinct row keys
 * @ param expectedCellsPerRow the expected number of column key / value mappings in each row
 * @ throws IllegalArgumentException if { @ code expectedRows } or { @ code expectedCellsPerRow } is
 * negative */
public static < R , C , V > HashBasedTable < R , C , V > create ( int expectedRows , int expectedCellsPerRow ) { } }

implementation: checkNonnegative ( expectedCellsPerRow , "expectedCellsPerRow" ) ; Map < R , Map < C , V > > backingMap = Maps . newLinkedHashMapWithExpectedSize ( expectedRows ) ; return new HashBasedTable < > ( backingMap , new Factory < C , V > ( expectedCellsPerRow ) ) ;


signature:
public class HashBasedTable { /** * Creates a { @ code HashBasedTable } with the same mappings as the specified table .
 * @ param table the table to copy
 * @ throws NullPointerException if any of the row keys , column keys , or values in { @ code table } is
 * null */
public static < R , C , V > HashBasedTable < R , C , V > create ( Table < ? extends R , ? extends C , ? extends V > table ) { } }

implementation: HashBasedTable < R , C , V > result = create ( ) ; result . putAll ( table ) ; return result ;


signature:
public class HashBasedTable { /** * Overriding so NullPointerTester test passes . */
@ Override public boolean contains ( @ NullableDecl Object rowKey , @ NullableDecl Object columnKey ) { } }

implementation: return super . contains ( rowKey , columnKey ) ;


signature:
public class Utf8 { /** * Returns the number of bytes in the UTF - 8 - encoded form of { @ code sequence } . For a string , this
 * method is equivalent to { @ code string . getBytes ( UTF _ 8 ) . length } , but is more efficient in both
 * time and space .
 * @ throws IllegalArgumentException if { @ code sequence } contains ill - formed UTF - 16 ( unpaired
 * surrogates ) */
public static int encodedLength ( CharSequence sequence ) { } }

implementation:
// Warning to maintainers : this implementation is highly optimized .
int utf16Length = sequence . length ( ) ; int utf8Length = utf16Length ; int i = 0 ; // This loop optimizes for pure ASCII .
while ( i < utf16Length && sequence . charAt ( i ) < 0x80 ) { i ++ ; } // This loop optimizes for chars less than 0x800.
for ( ; i < utf16Length ; i ++ ) { char c = sequence . charAt ( i ) ; if ( c < 0x800 ) { utf8Length += ( ( 0x7f - c ) >>> 31 ) ; // branch free !
} else { utf8Length += encodedLengthGeneral ( sequence , i ) ; break ; } } if ( utf8Length < utf16Length ) { // Necessary and sufficient condition for overflow because of maximum 3x expansion
throw new IllegalArgumentException ( "UTF-8 length does not fit in int: " + ( utf8Length + ( 1L << 32 ) ) ) ; } return utf8Length ;


signature:
public class Utf8 { /** * Returns whether the given byte array slice is a well - formed UTF - 8 byte sequence , as defined by
 * { @ link # isWellFormed ( byte [ ] ) } . Note that this can be false even when { @ code
 * isWellFormed ( bytes ) } is true .
 * @ param bytes the input buffer
 * @ param off the offset in the buffer of the first byte to read
 * @ param len the number of bytes to read from the buffer */
public static boolean isWellFormed ( byte [ ] bytes , int off , int len ) { } }

implementation:
int end = off + len ; checkPositionIndexes ( off , end , bytes . length ) ; // Look for the first non - ASCII character .
for ( int i = off ; i < end ; i ++ ) { if ( bytes [ i ] < 0 ) { return isWellFormedSlowPath ( bytes , i , end ) ; } } return true ;


signature:
public class TreeTraverser { /** * Returns a tree traverser that uses the given function to navigate from a node to its children .
 * This is useful if the function instance already exists , or so that you can supply a lambda
 * expressions . If those circumstances don ' t apply , you probably don ' t need to use this ; subclass
 * { @ code TreeTraverser } and implement its { @ link # children } method directly .
 * @ since 20.0
 * @ deprecated Use { @ link com . google . common . graph . Traverser # forTree } instead . If you are using a
 * lambda , these methods have exactly the same signature . */
@ Deprecated public static < T > TreeTraverser < T > using ( final Function < T , ? extends Iterable < T > > nodeToChildrenFunction ) { } }

implementation: checkNotNull ( nodeToChildrenFunction ) ; return new TreeTraverser < T > ( ) { @ Override public Iterable < T > children ( T root ) { return nodeToChildrenFunction . apply ( root ) ; } } ;


signature:
public class TreeTraverser { /** * Returns an unmodifiable iterable over the nodes in a tree structure , using pre - order traversal .
 * That is , each node ' s subtrees are traversed after the node itself is returned .
 * < p > No guarantees are made about the behavior of the traversal when nodes change while iteration
 * is in progress or when the iterators generated by { @ link # children } are advanced .
 * @ deprecated Use { @ link com . google . common . graph . Traverser # depthFirstPreOrder } instead , which has
 * the same behavior . */
@ Deprecated public final FluentIterable < T > preOrderTraversal ( final T root ) { } }

implementation: checkNotNull ( root ) ; return new FluentIterable < T > ( ) { @ Override public UnmodifiableIterator < T > iterator ( ) { return preOrderIterator ( root ) ; } @ Override public void forEach ( Consumer < ? super T > action ) { checkNotNull ( action ) ; new Consumer < T > ( ) { @ Override public void accept ( T t ) { action . accept ( t ) ; children ( t ) . forEach ( this ) ; } } . accept ( root ) ; } } ;


signature:
public class TreeTraverser { /** * Returns an unmodifiable iterable over the nodes in a tree structure , using post - order
 * traversal . That is , each node ' s subtrees are traversed before the node itself is returned .
 * < p > No guarantees are made about the behavior of the traversal when nodes change while iteration
 * is in progress or when the iterators generated by { @ link # children } are advanced .
 * @ deprecated Use { @ link com . google . common . graph . Traverser # depthFirstPostOrder } instead , which
 * has the same behavior . */
@ Deprecated public final FluentIterable < T > postOrderTraversal ( final T root ) { } }

implementation: checkNotNull ( root ) ; return new FluentIterable < T > ( ) { @ Override public UnmodifiableIterator < T > iterator ( ) { return postOrderIterator ( root ) ; } @ Override public void forEach ( Consumer < ? super T > action ) { checkNotNull ( action ) ; new Consumer < T > ( ) { @ Override public void accept ( T t ) { children ( t ) . forEach ( this ) ; action . accept ( t ) ; } } . accept ( root ) ; } } ;


signature:
public class Collections2 { /** * javadoc ? */
public static < E > Collection < E > filter ( Collection < E > unfiltered , Predicate < ? super E > predicate ) { } }

implementation:
if ( unfiltered instanceof FilteredCollection ) { // Support clear ( ) , removeAll ( ) , and retainAll ( ) when filtering a filtered
// collection .
return ( ( FilteredCollection < E > ) unfiltered ) . createCombined ( predicate ) ; } return new FilteredCollection < E > ( checkNotNull ( unfiltered ) , checkNotNull ( predicate ) ) ;


signature:
public class Collections2 { /** * Returns { @ code true } if the collection { @ code self } contains all of the elements in the
 * collection { @ code c } .
 * < p > This method iterates over the specified collection { @ code c } , checking each element returned
 * by the iterator in turn to see if it is contained in the specified collection { @ code self } . If
 * all elements are so contained , { @ code true } is returned , otherwise { @ code false } .
 * @ param self a collection which might contain all elements in { @ code c }
 * @ param c a collection whose elements might be contained by { @ code self } */
static boolean containsAllImpl ( Collection < ? > self , Collection < ? > c ) { } }

implementation: for ( Object o : c ) { if ( ! self . contains ( o ) ) { return false ; } } return true ;


signature:
public class Collections2 { /** * An implementation of { @ link Collection # toString ( ) } . */
static String toStringImpl ( final Collection < ? > collection ) { } }

implementation: StringBuilder sb = newStringBuilderForCollection ( collection . size ( ) ) . append ( '[' ) ; boolean first = true ; for ( Object o : collection ) { if ( ! first ) { sb . append ( ", " ) ; } first = false ; if ( o == collection ) { sb . append ( "(this Collection)" ) ; } else { sb . append ( o ) ; } } return sb . append ( ']' ) . toString ( ) ;


signature:
public class Collections2 { /** * Returns best - effort - sized StringBuilder based on the given collection size . */
static StringBuilder newStringBuilderForCollection ( int size ) { } }

implementation: checkNonnegative ( size , "size" ) ; return new StringBuilder ( ( int ) Math . min ( size * 8L , Ints . MAX_POWER_OF_TWO ) ) ;


signature:
public class Collections2 { /** * Used to avoid http : / / bugs . sun . com / view _ bug . do ? bug _ id = 6558557 */
static < T > Collection < T > cast ( Iterable < T > iterable ) { } }

implementation: return ( Collection < T > ) iterable ;


signature:
public class Collections2 { /** * Returns a { @ link Collection } of all the permutations of the specified { @ link Iterable } .
 * < p > < i > Notes : < / i > This is an implementation of the algorithm for Lexicographical Permutations
 * Generation , described in Knuth ' s " The Art of Computer Programming " , Volume 4 , Chapter 7,
 * Section 7.2.1.2 . The iteration order follows the lexicographical order . This means that the
 * first permutation will be in ascending order , and the last will be in descending order .
 * < p > Duplicate elements are considered equal . For example , the list [ 1 , 1 ] will have only one
 * permutation , instead of two . This is why the elements have to implement { @ link Comparable } .
 * < p > An empty iterable has only one permutation , which is an empty list .
 * < p > This method is equivalent to { @ code Collections2 . orderedPermutations ( list ,
 * Ordering . natural ( ) ) } .
 * @ param elements the original iterable whose elements have to be permuted .
 * @ return an immutable { @ link Collection } containing all the different permutations of the
 * original iterable .
 * @ throws NullPointerException if the specified iterable is null or has any null elements .
 * @ since 12.0 */
@ Beta public static < E extends Comparable < ? super E > > Collection < List < E > > orderedPermutations ( Iterable < E > elements ) { } }

implementation: return orderedPermutations ( elements , Ordering . natural ( ) ) ;


signature:
public class Collections2 { /** * Returns a { @ link Collection } of all the permutations of the specified { @ link Collection } .
 * < p > < i > Notes : < / i > This is an implementation of the Plain Changes algorithm for permutations
 * generation , described in Knuth ' s " The Art of Computer Programming " , Volume 4 , Chapter 7,
 * Section 7.2.1.2.
 * < p > If the input list contains equal elements , some of the generated permutations will be equal .
 * < p > An empty collection has only one permutation , which is an empty list .
 * @ param elements the original collection whose elements have to be permuted .
 * @ return an immutable { @ link Collection } containing all the different permutations of the
 * original collection .
 * @ throws NullPointerException if the specified collection is null or has any null elements .
 * @ since 12.0 */
@ Beta public static < E > Collection < List < E > > permutations ( Collection < E > elements ) { } }

implementation: return new PermutationCollection < E > ( ImmutableList . copyOf ( elements ) ) ;


signature:
public class Collections2 { /** * Returns { @ code true } if the second list is a permutation of the first . */
private static boolean isPermutation ( List < ? > first , List < ? > second ) { } }

implementation: if ( first . size ( ) != second . size ( ) ) { return false ; } ObjectCountHashMap < ? > firstCounts = counts ( first ) ; ObjectCountHashMap < ? > secondCounts = counts ( second ) ; if ( first . size ( ) != second . size ( ) ) { return false ; } for ( int i = 0 ; i < first . size ( ) ; i ++ ) { if ( firstCounts . getValue ( i ) != secondCounts . get ( firstCounts . getKey ( i ) ) ) { return false ; } } return true ;


signature:
public class HashMultimap { /** * Constructs a { @ code HashMultimap } with the same mappings as the specified multimap . If a
 * key - value mapping appears multiple times in the input multimap , it only appears once in the
 * constructed multimap .
 * < p > This method will soon be deprecated in favor of { @ code
 * MultimapBuilder . hashKeys ( ) . hashSetValues ( ) . build ( multimap ) } .
 * @ param multimap the multimap whose contents are copied to this multimap */
public static < K , V > HashMultimap < K , V > create ( Multimap < ? extends K , ? extends V > multimap ) { } }

implementation: return new HashMultimap < > ( multimap ) ;


signature:
public class TypeResolver { /** * Returns a resolver that resolves types " invariantly " .
 * < p > For example , when resolving { @ code List < T > } in the context of { @ code ArrayList < ? > } , { @ code
 * < T > } cannot be invariantly resolved to { @ code < ? > } because otherwise the parameter type of
 * { @ code List : : set } will be { @ code < ? > } and it ' ll falsely say any object can be passed into
 * { @ code ArrayList < ? > : : set } .
 * < p > Instead , { @ code < ? > } will be resolved to a capture in the form of a type variable { @ code
 * < capture - of - ? extends Object > } , effectively preventing { @ code set } from accepting any type . */
static TypeResolver invariantly ( Type contextType ) { } }

implementation: Type invariantContext = WildcardCapturer . INSTANCE . capture ( contextType ) ; return new TypeResolver ( ) . where ( TypeMappingIntrospector . getTypeMappings ( invariantContext ) ) ;


signature:
public class TypeResolver { /** * Returns a new { @ code TypeResolver } with type variables in { @ code formal } mapping to types in
 * { @ code actual } .
 * < p > For example , if { @ code formal } is a { @ code TypeVariable T } , and { @ code actual } is { @ code
 * String . class } , then { @ code new TypeResolver ( ) . where ( formal , actual ) } will { @ linkplain
 * # resolveType resolve } { @ code ParameterizedType List < T > } to { @ code List < String > } , and resolve
 * { @ code Map < T , Something > } to { @ code Map < String , Something > } etc . Similarly , { @ code formal } and
 * { @ code actual } can be { @ code Map < K , V > } and { @ code Map < String , Integer > } respectively , or they
 * can be { @ code E [ ] } and { @ code String [ ] } respectively , or even any arbitrary combination
 * thereof .
 * @ param formal The type whose type variables or itself is mapped to other type ( s ) . It ' s almost
 * always a bug if { @ code formal } isn ' t a type variable and contains no type variable . Make
 * sure you are passing the two parameters in the right order .
 * @ param actual The type that the formal type variable ( s ) are mapped to . It can be or contain yet
 * other type variables , in which case these type variables will be further resolved if
 * corresponding mappings exist in the current { @ code TypeResolver } instance . */
public TypeResolver where ( Type formal , Type actual ) { } }

implementation: Map < TypeVariableKey , Type > mappings = Maps . newHashMap ( ) ; populateTypeMappings ( mappings , checkNotNull ( formal ) , checkNotNull ( actual ) ) ; return where ( mappings ) ;


signature:
public class TypeResolver { /** * Returns a new { @ code TypeResolver } with { @ code variable } mapping to { @ code type } . */
TypeResolver where ( Map < TypeVariableKey , ? extends Type > mappings ) { } }

implementation: return new TypeResolver ( typeTable . where ( mappings ) ) ;


signature:
public class TypeResolver { /** * Resolves all type variables in { @ code type } and all downstream types and returns a
 * corresponding type with type variables resolved . */
public Type resolveType ( Type type ) { } }

implementation:
checkNotNull ( type ) ; if ( type instanceof TypeVariable ) { return typeTable . resolve ( ( TypeVariable < ? > ) type ) ; } else if ( type instanceof ParameterizedType ) { return resolveParameterizedType ( ( ParameterizedType ) type ) ; } else if ( type instanceof GenericArrayType ) { return resolveGenericArrayType ( ( GenericArrayType ) type ) ; } else if ( type instanceof WildcardType ) { return resolveWildcardType ( ( WildcardType ) type ) ; } else { // if Class < ? > , no resolution needed , we are done .
return type ; }


signature:
public class AbstractMapBasedMultimap { /** * Used during deserialization only . */
final void setMap ( Map < K , Collection < V > > map ) { } }

implementation: this . map = map ; totalSize = 0 ; for ( Collection < V > values : map . values ( ) ) { checkArgument ( ! values . isEmpty ( ) ) ; totalSize += values . size ( ) ; }


signature:
public class AbstractMapBasedMultimap { /** * { @ inheritDoc }
 * < p > The returned collection is immutable . */
@ Override public Collection < V > replaceValues ( @ NullableDecl K key , Iterable < ? extends V > values ) { } }

implementation:
Iterator < ? extends V > iterator = values . iterator ( ) ; if ( ! iterator . hasNext ( ) ) { return removeAll ( key ) ; } // TODO ( lowasser ) : investigate atomic failure ?
Collection < V > collection = getOrCreateCollection ( key ) ; Collection < V > oldValues = createCollection ( ) ; oldValues . addAll ( collection ) ; totalSize -= collection . size ( ) ; collection . clear ( ) ; while ( iterator . hasNext ( ) ) { if ( collection . add ( iterator . next ( ) ) ) { totalSize ++ ; } } return unmodifiableCollectionSubclass ( oldValues ) ;


signature:
public class AbstractMapBasedMultimap { /** * { @ inheritDoc }
 * < p > The returned collection is immutable . */
@ Override public Collection < V > removeAll ( @ NullableDecl Object key ) { } }

implementation: Collection < V > collection = map . remove ( key ) ; if ( collection == null ) { return createUnmodifiableEmptyCollection ( ) ; } Collection < V > output = createCollection ( ) ; output . addAll ( collection ) ; totalSize -= collection . size ( ) ; collection . clear ( ) ; return unmodifiableCollectionSubclass ( output ) ;


signature:
public class AbstractMapBasedMultimap { /** * Removes all values for the provided key . */
private void removeValuesForKey ( Object key ) { } }

implementation: Collection < V > collection = Maps . safeRemove ( map , key ) ; if ( collection != null ) { int count = collection . size ( ) ; collection . clear ( ) ; totalSize -= count ; }


signature:
public class Joiner { /** * Appends to { @ code appendable } the string representation of each of the remaining arguments . */
@ CanIgnoreReturnValue public final < A extends Appendable > A appendTo ( A appendable , @ NullableDecl Object first , @ NullableDecl Object second , Object ... rest ) throws IOException { } }

implementation: return appendTo ( appendable , iterable ( first , second , rest ) ) ;


signature:
public class Joiner { /** * Returns a string containing the string representation of each argument , using the previously
 * configured separator between each . */
public final String join ( @ NullableDecl Object first , @ NullableDecl Object second , Object ... rest ) { } }

implementation: return join ( iterable ( first , second , rest ) ) ;


signature:
public class Striped { /** * Creates a { @ code Striped < L > } with eagerly initialized , strongly referenced locks . Every lock is
 * obtained from the passed supplier .
 * @ param stripes the minimum number of stripes ( locks ) required
 * @ param supplier a { @ code Supplier < L > } object to obtain locks from
 * @ return a new { @ code Striped < L > } */
static < L > Striped < L > custom ( int stripes , Supplier < L > supplier ) { } }

implementation: return new CompactStriped < > ( stripes , supplier ) ;


signature:
public class Striped { /** * Creates a { @ code Striped < Lock > } with eagerly initialized , strongly referenced locks . Every lock
 * is reentrant .
 * @ param stripes the minimum number of stripes ( locks ) required
 * @ return a new { @ code Striped < Lock > } */
public static Striped < Lock > lock ( int stripes ) { } }

implementation: return custom ( stripes , new Supplier < Lock > ( ) { @ Override public Lock get ( ) { return new PaddedLock ( ) ; } } ) ;


signature:
public class Striped { /** * Creates a { @ code Striped < Lock > } with lazily initialized , weakly referenced locks . Every lock is
 * reentrant .
 * @ param stripes the minimum number of stripes ( locks ) required
 * @ return a new { @ code Striped < Lock > } */
public static Striped < Lock > lazyWeakLock ( int stripes ) { } }

implementation: return lazy ( stripes , new Supplier < Lock > ( ) { @ Override public Lock get ( ) { return new ReentrantLock ( false ) ; } } ) ;


signature:
public class Striped { /** * Creates a { @ code Striped < Semaphore > } with eagerly initialized , strongly referenced semaphores ,
 * with the specified number of permits .
 * @ param stripes the minimum number of stripes ( semaphores ) required
 * @ param permits the number of permits in each semaphore
 * @ return a new { @ code Striped < Semaphore > } */
public static Striped < Semaphore > semaphore ( int stripes , final int permits ) { } }

implementation: return custom ( stripes , new Supplier < Semaphore > ( ) { @ Override public Semaphore get ( ) { return new PaddedSemaphore ( permits ) ; } } ) ;


signature:
public class Striped { /** * Creates a { @ code Striped < Semaphore > } with lazily initialized , weakly referenced semaphores ,
 * with the specified number of permits .
 * @ param stripes the minimum number of stripes ( semaphores ) required
 * @ param permits the number of permits in each semaphore
 * @ return a new { @ code Striped < Semaphore > } */
public static Striped < Semaphore > lazyWeakSemaphore ( int stripes , final int permits ) { } }

implementation: return lazy ( stripes , new Supplier < Semaphore > ( ) { @ Override public Semaphore get ( ) { return new Semaphore ( permits , false ) ; } } ) ;


signature:
public class Sets { /** * Returns a { @ code Collector } that accumulates the input elements into a new { @ code ImmutableSet }
 * with an implementation specialized for enums . Unlike { @ link ImmutableSet # toImmutableSet } , the
 * resulting set will iterate over elements in their enum definition order , not encounter order .
 * @ since 21.0 */
public static < E extends Enum < E > > Collector < E , ? , ImmutableSet < E > > toImmutableEnumSet ( ) { } }

implementation: return ( Collector ) Accumulator . TO_IMMUTABLE_ENUM_SET ;


signature:
public class FluentIterable { /** * Returns a fluent iterable that wraps { @ code iterable } , or { @ code iterable } itself if it is
 * already a { @ code FluentIterable } .
 * < p > < b > { @ code Stream } equivalent : < / b > { @ link Collection # stream } if { @ code iterable } is a { @ link
 * Collection } ; { @ link Streams # stream ( Iterable ) } otherwise . */
public static < E > FluentIterable < E > from ( final Iterable < E > iterable ) { } }

implementation: return ( iterable instanceof FluentIterable ) ? ( FluentIterable < E > ) iterable : new FluentIterable < E > ( iterable ) { @ Override public Iterator < E > iterator ( ) { return iterable . iterator ( ) ; } } ;


signature:
public class FluentIterable { /** * Returns a fluent iterable containing { @ code elements } in the specified order .
 * < p > The returned iterable is an unmodifiable view of the input array .
 * < p > < b > { @ code Stream } equivalent : < / b > { @ link java . util . stream . Stream # of ( Object [ ] )
 * Stream . of ( T . . . ) } .
 * @ since 20.0 ( since 18.0 as an overload of { @ code of } ) */
@ Beta public static < E > FluentIterable < E > from ( E [ ] elements ) { } }

implementation: return from ( Arrays . asList ( elements ) ) ;


signature:
public class FluentIterable { /** * Construct a fluent iterable from another fluent iterable . This is obviously never necessary ,
 * but is intended to help call out cases where one migration from { @ code Iterable } to { @ code
 * FluentIterable } has obviated the need to explicitly convert to a { @ code FluentIterable } .
 * @ deprecated instances of { @ code FluentIterable } don ' t need to be converted to { @ code
 * FluentIterable } */
@ Deprecated public static < E > FluentIterable < E > from ( FluentIterable < E > iterable ) { } }

implementation: return checkNotNull ( iterable ) ;


signature:
public class FluentIterable { /** * Returns a fluent iterable that combines several iterables . 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 > { @ code Stream } equivalent : < / b > to concatenate an arbitrary number of streams , use { @ code
 * Stream . of ( stream1 , stream2 , . . . ) . flatMap ( s - > s ) } . If the sources are iterables , use { @ code
 * Stream . of ( iter1 , iter2 , . . . ) . flatMap ( Streams : : stream ) } .
 * @ throws NullPointerException if any of the provided iterables is { @ code null }
 * @ since 20.0 */
@ Beta public static < T > FluentIterable < T > concat ( Iterable < ? extends T > ... inputs ) { } }

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


signature:
public class FluentIterable { /** * Returns a fluent iterable that combines several iterables . 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 . The methods of the returned iterable may throw { @ code
 * NullPointerException } if any of the input iterators is { @ code null } .
 * < p > < b > { @ code Stream } equivalent : < / b > { @ code streamOfStreams . flatMap ( s - > s ) } or { @ code
 * streamOfIterables . flatMap ( Streams : : stream ) } . ( See { @ link Streams # stream } . )
 * @ since 20.0 */
@ Beta public static < T > FluentIterable < T > concat ( final Iterable < ? extends Iterable < ? extends T > > inputs ) { } }

implementation: checkNotNull ( inputs ) ; return new FluentIterable < T > ( ) { @ Override public Iterator < T > iterator ( ) { return Iterators . concat ( Iterators . transform ( inputs . iterator ( ) , Iterables . < T > toIterator ( ) ) ) ; } } ;


signature:
public class FluentIterable { /** * Concatenates a varargs array of iterables without making a defensive copy of the array . */
private static < T > FluentIterable < T > concatNoDefensiveCopy ( final Iterable < ? extends T > ... inputs ) { } }

implementation:
for ( Iterable < ? extends T > input : inputs ) { checkNotNull ( input ) ; } return new FluentIterable < T > ( ) { @ Override public Iterator < T > iterator ( ) { return Iterators . concat ( /* lazily generate the iterators on each input only as needed */
new AbstractIndexedListIterator < Iterator < ? extends T > > ( inputs . length ) { @ Override public Iterator < ? extends T > get ( int i ) { return inputs [ i ] . iterator ( ) ; } } ) ; } } ;


signature:
public class FluentIterable { /** * Returns a fluent iterable containing no elements .
 * < p > < b > { @ code Stream } equivalent : < / b > { @ link Stream # empty } .
 * @ since 20.0 */
@ Beta public static < E > FluentIterable < E > of ( ) { } }

implementation: return FluentIterable . from ( ImmutableList . < E > of ( ) ) ;


signature:
public class FluentIterable { /** * Returns a fluent iterable containing the specified elements in order .
 * < p > < b > { @ code Stream } equivalent : < / b > { @ link java . util . stream . Stream # of ( Object [ ] )
 * Stream . of ( T . . . ) } .
 * @ since 20.0 */
@ Beta public static < E > FluentIterable < E > of ( @ Nullable E element , E ... elements ) { } }

implementation: return from ( Lists . asList ( element , elements ) ) ;


signature:
public class FluentIterable { /** * Returns a fluent iterable whose iterators traverse first the elements of this fluent iterable ,
 * followed by those of { @ code other } . The iterators are not polled until necessary .
 * < p > The returned iterable ' s { @ code Iterator } supports { @ code remove ( ) } when the corresponding
 * { @ code Iterator } supports it .
 * < p > < b > { @ code Stream } equivalent : < / b > { @ link Stream # concat } .
 * @ since 18.0 */
@ Beta public final FluentIterable < E > append ( Iterable < ? extends E > other ) { } }

implementation: return FluentIterable . concat ( getDelegate ( ) , other ) ;


signature:
public class FluentIterable { /** * Returns the elements from this fluent iterable that satisfy a predicate . The resulting fluent
 * iterable ' s iterator does not support { @ code remove ( ) } .
 * < p > < b > { @ code Stream } equivalent : < / b > { @ link Stream # filter } ( same ) . */
public final FluentIterable < E > filter ( Predicate < ? super E > predicate ) { } }

implementation: return from ( Iterables . filter ( getDelegate ( ) , predicate ) ) ;


signature:
public class FluentIterable { /** * Returns the elements from this fluent iterable that are instances of class { @ code type } .
 * < 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 > */
@ GwtIncompatible // Class . isInstance
public final < T > FluentIterable < T > filter ( Class < T > type ) { } }

implementation: return from ( Iterables . filter ( getDelegate ( ) , type ) ) ;


signature:
public class FluentIterable { /** * Returns an { @ link Optional } containing the first element in this fluent 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 this fluent iterable , a { @ link NullPointerException } will be thrown .
 * < p > < b > { @ code Stream } equivalent : < / b > { @ code stream . filter ( predicate ) . findFirst ( ) } . */
public final Optional < E > firstMatch ( Predicate < ? super E > predicate ) { } }

implementation: return Iterables . tryFind ( getDelegate ( ) , predicate ) ;


signature:
public class FluentIterable { /** * Returns an { @ link Optional } containing the first element in this fluent iterable . If the
 * iterable is empty , { @ code Optional . absent ( ) } is returned .
 * < p > < b > { @ code Stream } equivalent : < / b > if the goal is to obtain any element , { @ link
 * Stream # findAny } ; if it must specifically be the < i > first < / i > element , { @ code Stream # findFirst } .
 * @ throws NullPointerException if the first element is null ; if this is a possibility , use { @ code
 * iterator ( ) . next ( ) } or { @ link Iterables # getFirst } instead . */
public final Optional < E > first ( ) { } }

implementation: Iterator < E > iterator = getDelegate ( ) . iterator ( ) ; return iterator . hasNext ( ) ? Optional . of ( iterator . next ( ) ) : Optional . < E > absent ( ) ;


signature:
public class FluentIterable { /** * Returns an { @ link Optional } containing the last element in this fluent iterable . If the
 * iterable is empty , { @ code Optional . absent ( ) } is returned . If the underlying { @ code iterable } is
 * a { @ link List } with { @ link java . util . RandomAccess } support , then this operation is guaranteed
 * to be { @ code O ( 1 ) } .
 * < p > < b > { @ code Stream } equivalent : < / b > { @ code stream . reduce ( ( a , b ) - > b ) } .
 * @ throws NullPointerException if the last element is null ; if this is a possibility , use { @ link
 * Iterables # getLast } instead . */
public final Optional < E > last ( ) { } }

implementation:
// Iterables # getLast was inlined here so we don ' t have to throw / catch a NSEE
// TODO ( kevinb ) : Support a concurrently modified collection ?
Iterable < E > iterable = getDelegate ( ) ; if ( iterable instanceof List ) { List < E > list = ( List < E > ) iterable ; if ( list . isEmpty ( ) ) { return Optional . absent ( ) ; } return Optional . of ( list . get ( list . size ( ) - 1 ) ) ; } Iterator < E > iterator = iterable . iterator ( ) ; if ( ! iterator . hasNext ( ) ) { return Optional . absent ( ) ; } /* * TODO ( kevinb ) : consider whether this " optimization " is worthwhile . Users with SortedSets tend
 * to know they are SortedSets and probably would not call this method . */
if ( iterable instanceof SortedSet ) { SortedSet < E > sortedSet = ( SortedSet < E > ) iterable ; return Optional . of ( sortedSet . last ( ) ) ; } while ( true ) { E current = iterator . next ( ) ; if ( ! iterator . hasNext ( ) ) { return Optional . of ( current ) ; } }


signature:
public class FluentIterable { /** * Returns an { @ code ImmutableSortedSet } containing all of the elements from this { @ code
 * FluentIterable } in the order specified by { @ code comparator } , with duplicates ( determined by
 * { @ code comparator . compare ( x , y ) = = 0 } ) removed . To produce an { @ code ImmutableSortedSet } sorted
 * by its natural ordering , use { @ code toSortedSet ( Ordering . natural ( ) ) } .
 * < p > < b > { @ code Stream } equivalent : < / b > pass { @ link ImmutableSortedSet # toImmutableSortedSet } to
 * { @ code stream . collect ( ) } .
 * @ param comparator the function by which to sort set elements
 * @ throws NullPointerException if any element of this iterable is { @ code null }
 * @ since 14.0 ( since 12.0 as { @ code toImmutableSortedSet ( ) } ) . */
public final ImmutableSortedSet < E > toSortedSet ( Comparator < ? super E > comparator ) { } }

implementation: return ImmutableSortedSet . copyOf ( comparator , getDelegate ( ) ) ;


signature:
public class FluentIterable { /** * Returns an immutable map whose keys are the distinct elements of this { @ code FluentIterable }
 * and whose value for each key was computed by { @ code valueFunction } . The map ' s iteration order
 * is the order of the first appearance of each key in this iterable .
 * < p > When there are multiple instances of a key in this iterable , it is unspecified whether
 * { @ code valueFunction } will be applied to more than one instance of that key and , if it is ,
 * which result will be mapped to that key in the returned map .
 * < p > < b > { @ code Stream } equivalent : < / b > { @ code stream . collect ( ImmutableMap . toImmutableMap ( k - > k ,
 * valueFunction ) ) } .
 * @ throws NullPointerException if any element of this iterable is { @ code null } , or if { @ code
 * valueFunction } produces { @ code null } for any key
 * @ since 14.0 */
public final < V > ImmutableMap < E , V > toMap ( Function < ? super E , V > valueFunction ) { } }

implementation: return Maps . toMap ( getDelegate ( ) , valueFunction ) ;


signature:
public class FluentIterable { /** * Creates an index { @ code ImmutableListMultimap } that contains the results of applying a
 * specified function to each item in this { @ code FluentIterable } of values . Each element of this
 * iterable will be stored as a value in the resulting multimap , yielding a multimap with the same
 * size as this iterable . The key used to store that value in the multimap will be the result of
 * calling the function on that value . The resulting multimap is created as an immutable snapshot .
 * In the returned multimap , keys appear in the order they are first encountered , and the values
 * corresponding to each key appear in the same order as they are encountered .
 * < p > < b > { @ code Stream } equivalent : < / b > { @ code stream . collect ( Collectors . groupingBy ( keyFunction ) ) }
 * behaves similarly , but returns a mutable { @ code Map < K , List < E > > } instead , and may not preserve
 * the order of entries ) .
 * @ param keyFunction the function used to produce the key for each value
 * @ throws NullPointerException if any element of this iterable is { @ code null } , or if { @ code
 * keyFunction } produces { @ code null } for any key
 * @ since 14.0 */
public final < K > ImmutableListMultimap < K , E > index ( Function < ? super E , K > keyFunction ) { } }

implementation: return Multimaps . index ( getDelegate ( ) , keyFunction ) ;


signature:
public class FluentIterable { /** * Returns a map with the contents of this { @ code FluentIterable } as its { @ code values } , indexed
 * by keys derived from those values . In other words , each input value produces an entry in the
 * map whose key is the result of applying { @ code keyFunction } to that value . These entries appear
 * in the same order as they appeared in this fluent iterable . Example usage :
 * < pre > { @ code
 * Color red = new Color ( " red " , 255 , 0 , 0 ) ;
 * FluentIterable < Color > allColors = FluentIterable . from ( ImmutableSet . of ( red , green , blue ) ) ;
 * Map < String , Color > colorForName = allColors . uniqueIndex ( toStringFunction ( ) ) ;
 * assertThat ( colorForName ) . containsEntry ( " red " , red ) ;
 * } < / pre >
 * < p > If your index may associate multiple values with each key , use { @ link # index ( Function )
 * index } .
 * < p > < b > { @ code Stream } equivalent : < / b > { @ code
 * stream . collect ( ImmutableMap . toImmutableMap ( keyFunction , v - > v ) ) } .
 * @ param keyFunction the function used to produce the key for each value
 * @ return a map mapping the result of evaluating the function { @ code keyFunction } on each value
 * in this fluent iterable to that value
 * @ throws IllegalArgumentException if { @ code keyFunction } produces the same key for more than one
 * value in this fluent iterable
 * @ throws NullPointerException if any element of this iterable is { @ code null } , or if { @ code
 * keyFunction } produces { @ code null } for any key
 * @ since 14.0 */
public final < K > ImmutableMap < K , E > uniqueIndex ( Function < ? super E , K > keyFunction ) { } }

implementation: return Maps . uniqueIndex ( getDelegate ( ) , keyFunction ) ;


signature:
public class FluentIterable { /** * Returns an array containing all of the elements from this fluent iterable in iteration order .
 * < p > < b > { @ code Stream } equivalent : < / b > if an object array is acceptable , use { @ code
 * stream . toArray ( ) } ; if { @ code type } is a class literal such as { @ code MyType . class } , use { @ code
 * stream . toArray ( MyType [ ] : : new ) } . Otherwise use { @ code stream . toArray ( len - > ( E [ ] )
 * Array . newInstance ( type , len ) ) } .
 * @ param type the type of the elements
 * @ return a newly - allocated array into which all the elements of this fluent iterable have been
 * copied */
@ GwtIncompatible // Array . newArray ( Class , int )
public final E [ ] toArray ( Class < E > type ) { } }

implementation: return Iterables . toArray ( getDelegate ( ) , type ) ;


signature:
public class Atomics { /** * Creates an { @ code AtomicReference } instance with the given initial value .
 * @ param initialValue the initial value
 * @ return a new { @ code AtomicReference } with the given initial value */
public static < V > AtomicReference < V > newReference ( @ NullableDecl V initialValue ) { } }

implementation: return new AtomicReference < V > ( initialValue ) ;


signature:
public class ImmutableMultimap { /** * Returns an immutable multimap containing a single entry . */
public static < K , V > ImmutableMultimap < K , V > of ( K k1 , V v1 ) { } }

implementation: return ImmutableListMultimap . of ( k1 , v1 ) ;


signature:
public class ImmutableMultimap { /** * Returns an immutable multimap containing the given entries , in order . */
public static < K , V > ImmutableMultimap < K , V > of ( K k1 , V v1 , K k2 , V v2 ) { } }

implementation: return ImmutableListMultimap . of ( k1 , v1 , k2 , v2 ) ;


signature:
public class ImmutableMultimap { /** * Returns an immutable multimap containing the same mappings as { @ code multimap } , in the
 * " key - grouped " iteration order described in the class documentation .
 * < 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 > ImmutableMultimap < K , V > copyOf ( Multimap < ? extends K , ? extends V > multimap ) { } }

implementation:
if ( multimap instanceof ImmutableMultimap ) { @ SuppressWarnings ( "unchecked" ) // safe since multimap is not writable
ImmutableMultimap < K , V > kvMultimap = ( ImmutableMultimap < K , V > ) multimap ; if ( ! kvMultimap . isPartialView ( ) ) { return kvMultimap ; } } return ImmutableListMultimap . copyOf ( multimap ) ;


signature:
public class ImmutableMultimap { /** * Returns an immutable multimap containing the specified entries . The returned multimap iterates
 * over keys in the order they were first encountered in the input , and the values for each key
 * are iterated in the order they were encountered .
 * @ throws NullPointerException if any key , value , or entry is null
 * @ since 19.0 */
@ Beta public static < K , V > ImmutableMultimap < K , V > copyOf ( Iterable < ? extends Entry < ? extends K , ? extends V > > entries ) { } }

implementation: return ImmutableListMultimap . copyOf ( entries ) ;


signature:
public class ImmutableMultimap { /** * Guaranteed to throw an exception and leave the multimap unmodified .
 * @ throws UnsupportedOperationException always
 * @ deprecated Unsupported operation . */
@ CanIgnoreReturnValue @ Deprecated @ Override public ImmutableCollection < V > replaceValues ( K key , Iterable < ? extends V > values ) { } }

implementation: throw new UnsupportedOperationException ( ) ;


signature:
public class ImmutableMultimap { /** * Guaranteed to throw an exception and leave the multimap unmodified .
 * @ throws UnsupportedOperationException always
 * @ deprecated Unsupported operation . */
@ CanIgnoreReturnValue @ Deprecated @ Override public boolean putAll ( K key , Iterable < ? extends V > values ) { } }


signature:
public class ImmutableMultimap { /** * Returns an immutable collection of all key - value pairs in the multimap . */
@ Override public ImmutableCollection < Entry < K , V > > entries ( ) { } }

implementation: return ( ImmutableCollection < Entry < K , V > > ) super . entries ( ) ;


signature:
public class Graphs { /** * Returns true if { @ code network } has at least one cycle . A cycle is defined as a non - empty
 * subset of edges in a graph arranged to form a path ( a sequence of adjacent outgoing edges )
 * starting and ending with the same node .
 * < p > This method will detect any non - empty cycle , including self - loops ( a cycle of length 1 ) . */
public static boolean hasCycle ( Network < ? , ? > network ) { } }

implementation:
// In a directed graph , parallel edges cannot introduce a cycle in an acyclic graph .
// However , in an undirected graph , any parallel edge induces a cycle in the graph .
if ( ! network . isDirected ( ) && network . allowsParallelEdges ( ) && network . edges ( ) . size ( ) > network . asGraph ( ) . edges ( ) . size ( ) ) { return true ; } return hasCycle ( network . asGraph ( ) ) ;


signature:
public class Graphs { /** * Performs a traversal of the nodes reachable from { @ code node } . If we ever reach a node we ' ve
 * already visited ( following only outgoing edges and without reusing edges ) , we know there ' s a
 * cycle in the graph . */
private static < N > boolean subgraphHasCycle ( Graph < N > graph , Map < Object , NodeVisitState > visitedNodes , N node , @ NullableDecl N previousNode ) { } }

implementation: NodeVisitState state = visitedNodes . get ( node ) ; if ( state == NodeVisitState . COMPLETE ) { return false ; } if ( state == NodeVisitState . PENDING ) { return true ; } visitedNodes . put ( node , NodeVisitState . PENDING ) ; for ( N nextNode : graph . successors ( node ) ) { if ( canTraverseWithoutReusingEdge ( graph , nextNode , previousNode ) && subgraphHasCycle ( graph , visitedNodes , nextNode , node ) ) { return true ; } } visitedNodes . put ( node , NodeVisitState . COMPLETE ) ; return false ;


signature:
public class Graphs { /** * TODO ( b / 31438252 ) : Consider potential optimizations for this algorithm . */
public static < N > Graph < N > transitiveClosure ( Graph < N > graph ) { } }

implementation:
MutableGraph < N > transitiveClosure = GraphBuilder . from ( graph ) . allowsSelfLoops ( true ) . build ( ) ; // Every node is , at a minimum , reachable from itself . Since the resulting transitive closure
// will have no isolated nodes , we can skip adding nodes explicitly and let putEdge ( ) do it .
if ( graph . isDirected ( ) ) { // Note : works for both directed and undirected graphs , but we only use in the directed case .
for ( N node : graph . nodes ( ) ) { for ( N reachableNode : reachableNodes ( graph , node ) ) { transitiveClosure . putEdge ( node , reachableNode ) ; } } } else { // An optimization for the undirected case : for every node B reachable from node A ,
// node A and node B have the same reachability set .
Set < N > visitedNodes = new HashSet < N > ( ) ; for ( N node : graph . nodes ( ) ) { if ( ! visitedNodes . contains ( node ) ) { Set < N > reachableNodes = reachableNodes ( graph , node ) ; visitedNodes . addAll ( reachableNodes ) ; int pairwiseMatch = 1 ; // start at 1 to include self - loops
for ( N nodeU : reachableNodes ) { for ( N nodeV : Iterables . limit ( reachableNodes , pairwiseMatch ++ ) ) { transitiveClosure . putEdge ( nodeU , nodeV ) ; } } } } } return transitiveClosure ;


signature:
public class Graphs { /** * Returns the set of nodes that are reachable from { @ code node } . Node B is defined as reachable
 * from node A if there exists a path ( a sequence of adjacent outgoing edges ) starting at node A
 * and ending at node B . Note that a node is always reachable from itself via a zero - length path .
 * < p > This is a " snapshot " based on the current topology of { @ code graph } , rather than a live view
 * of the set of nodes reachable from { @ code node } . In other words , the returned { @ link Set } will
 * not be updated after modifications to { @ code graph } .
 * @ throws IllegalArgumentException if { @ code node } is not present in { @ code graph } */
public static < N > Set < N > reachableNodes ( Graph < N > graph , N node ) { } }

implementation:
checkArgument ( graph . nodes ( ) . contains ( node ) , NODE_NOT_IN_GRAPH , node ) ; Set < N > visitedNodes = new LinkedHashSet < N > ( ) ; Queue < N > queuedNodes = new ArrayDeque < N > ( ) ; visitedNodes . add ( node ) ; queuedNodes . add ( node ) ; // Perform a breadth - first traversal rooted at the input node .
while ( ! queuedNodes . isEmpty ( ) ) { N currentNode = queuedNodes . remove ( ) ; for ( N successor : graph . successors ( currentNode ) ) { if ( visitedNodes . add ( successor ) ) { queuedNodes . add ( successor ) ; } } } return Collections . unmodifiableSet ( visitedNodes ) ;


signature:
public class Graphs { /** * Returns a view of { @ code graph } with the direction ( if any ) of every edge reversed . All other
 * properties remain intact , and further updates to { @ code graph } will be reflected in the view . */
public static < N > Graph < N > transpose ( Graph < N > graph ) { } }

implementation:
if ( ! graph . isDirected ( ) ) { return graph ; // the transpose of an undirected graph is an identical graph
} if ( graph instanceof TransposedGraph ) { return ( ( TransposedGraph < N > ) graph ) . graph ; } return new TransposedGraph < N > ( graph ) ;


signature:
public class Graphs { /** * Returns the subgraph of { @ code graph } induced by { @ code nodes } . This subgraph is a new graph
 * that contains all of the nodes in { @ code nodes } , and all of the { @ link Graph # edges ( ) edges }
 * from { @ code graph } for which both nodes are contained by { @ code nodes } .
 * @ throws IllegalArgumentException if any element in { @ code nodes } is not a node in the graph */
public static < N > MutableGraph < N > inducedSubgraph ( Graph < N > graph , Iterable < ? extends N > nodes ) { } }

implementation: MutableGraph < N > subgraph = ( nodes instanceof Collection ) ? GraphBuilder . from ( graph ) . expectedNodeCount ( ( ( Collection ) nodes ) . size ( ) ) . build ( ) : GraphBuilder . from ( graph ) . build ( ) ; for ( N node : nodes ) { subgraph . addNode ( node ) ; } for ( N node : subgraph . nodes ( ) ) { for ( N successorNode : graph . successors ( node ) ) { if ( subgraph . nodes ( ) . contains ( successorNode ) ) { subgraph . putEdge ( node , successorNode ) ; } } } return subgraph ;


signature:
public class Graphs { /** * Returns the subgraph of { @ code graph } induced by { @ code nodes } . This subgraph is a new graph
 * that contains all of the nodes in { @ code nodes } , and all of the { @ link Graph # edges ( ) edges }
 * ( and associated edge values ) from { @ code graph } for which both nodes are contained by { @ code
 * nodes } .
 * @ throws IllegalArgumentException if any element in { @ code nodes } is not a node in the graph */
public static < N , V > MutableValueGraph < N , V > inducedSubgraph ( ValueGraph < N , V > graph , Iterable < ? extends N > nodes ) { } }

implementation: MutableValueGraph < N , V > subgraph = ( nodes instanceof Collection ) ? ValueGraphBuilder . from ( graph ) . expectedNodeCount ( ( ( Collection ) nodes ) . size ( ) ) . build ( ) : ValueGraphBuilder . from ( graph ) . build ( ) ; for ( N node : nodes ) { subgraph . addNode ( node ) ; } for ( N node : subgraph . nodes ( ) ) { for ( N successorNode : graph . successors ( node ) ) { if ( subgraph . nodes ( ) . contains ( successorNode ) ) { subgraph . putEdgeValue ( node , successorNode , graph . edgeValueOrDefault ( node , successorNode , null ) ) ; } } } return subgraph ;


signature:
public class Graphs { /** * Returns the subgraph of { @ code network } induced by { @ code nodes } . This subgraph is a new graph
 * that contains all of the nodes in { @ code nodes } , and all of the { @ link Network # edges ( ) edges }
 * from { @ code network } for which the { @ link Network # incidentNodes ( Object ) incident nodes } are
 * both contained by { @ code nodes } .
 * @ throws IllegalArgumentException if any element in { @ code nodes } is not a node in the graph */
public static < N , E > MutableNetwork < N , E > inducedSubgraph ( Network < N , E > network , Iterable < ? extends N > nodes ) { } }

implementation: MutableNetwork < N , E > subgraph = ( nodes instanceof Collection ) ? NetworkBuilder . from ( network ) . expectedNodeCount ( ( ( Collection ) nodes ) . size ( ) ) . build ( ) : NetworkBuilder . from ( network ) . build ( ) ; for ( N node : nodes ) { subgraph . addNode ( node ) ; } for ( N node : subgraph . nodes ( ) ) { for ( E edge : network . outEdges ( node ) ) { N successorNode = network . incidentNodes ( edge ) . adjacentNode ( node ) ; if ( subgraph . nodes ( ) . contains ( successorNode ) ) { subgraph . addEdge ( node , successorNode , edge ) ; } } } return subgraph ;


signature:
public class Graphs { /** * Creates a mutable copy of { @ code graph } with the same nodes and edges . */
public static < N > MutableGraph < N > copyOf ( Graph < N > graph ) { } }

implementation: MutableGraph < N > copy = GraphBuilder . from ( graph ) . expectedNodeCount ( graph . nodes ( ) . size ( ) ) . build ( ) ; for ( N node : graph . nodes ( ) ) { copy . addNode ( node ) ; } for ( EndpointPair < N > edge : graph . edges ( ) ) { copy . putEdge ( edge . nodeU ( ) , edge . nodeV ( ) ) ; } return copy ;


signature:
public class Graphs { /** * Creates a mutable copy of { @ code graph } with the same nodes , edges , and edge values . */
public static < N , V > MutableValueGraph < N , V > copyOf ( ValueGraph < N , V > graph ) { } }

implementation: MutableValueGraph < N , V > copy = ValueGraphBuilder . from ( graph ) . expectedNodeCount ( graph . nodes ( ) . size ( ) ) . build ( ) ; for ( N node : graph . nodes ( ) ) { copy . addNode ( node ) ; } for ( EndpointPair < N > edge : graph . edges ( ) ) { copy . putEdgeValue ( edge . nodeU ( ) , edge . nodeV ( ) , graph . edgeValueOrDefault ( edge . nodeU ( ) , edge . nodeV ( ) , null ) ) ; } return copy ;


signature:
public class Graphs { /** * Creates a mutable copy of { @ code network } with the same nodes and edges . */
public static < N , E > MutableNetwork < N , E > copyOf ( Network < N , E > network ) { } }

implementation: MutableNetwork < N , E > copy = NetworkBuilder . from ( network ) . expectedNodeCount ( network . nodes ( ) . size ( ) ) . expectedEdgeCount ( network . edges ( ) . size ( ) ) . build ( ) ; for ( N node : network . nodes ( ) ) { copy . addNode ( node ) ; } for ( E edge : network . edges ( ) ) { EndpointPair < N > endpointPair = network . incidentNodes ( edge ) ; copy . addEdge ( endpointPair . nodeU ( ) , endpointPair . nodeV ( ) , edge ) ; } return copy ;


signature:
public class ByteSource { /** * Opens a new buffered { @ link InputStream } for reading from this source . The returned stream is
 * not required to be a { @ link BufferedInputStream } 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 ByteArrayInputStream } ) . 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 BufferedInputStream } ) */
public InputStream openBufferedStream ( ) throws IOException { } }

implementation: InputStream in = openStream ( ) ; return ( in instanceof BufferedInputStream ) ? ( BufferedInputStream ) in : new BufferedInputStream ( in ) ;


signature:
public class ByteSource { /** * Returns whether the source has zero bytes . The default implementation first checks { @ link
 * # sizeIfKnown } , returning true if it ' s known to be zero and false if it ' s known to be non - zero .
 * If the size is not known , it falls back to opening a stream and checking for EOF .
 * < p > Note that , in cases where { @ code sizeIfKnown } returns zero , it is < i > possible < / i > that bytes
 * are actually available for reading . ( For example , some special files may return a size of 0
 * despite actually having content when read . ) 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 > sizeIfKnown = sizeIfKnown ( ) ; if ( sizeIfKnown . isPresent ( ) ) { return sizeIfKnown . get ( ) == 0L ; } Closer closer = Closer . create ( ) ; try { InputStream in = closer . register ( openStream ( ) ) ; return in . read ( ) == - 1 ; } catch ( Throwable e ) { throw closer . rethrow ( e ) ; } finally { closer . close ( ) ; }


signature:
public class ByteSource { /** * Returns the size of this source in bytes , even if doing so requires opening and traversing an
 * entire stream . To avoid a potentially expensive operation , see { @ link # sizeIfKnown } .
 * < p > The default implementation calls { @ link # sizeIfKnown } and returns the value if present . If
 * absent , it will fall back to a heavyweight operation that will open a stream , read ( or { @ link
 * InputStream # skip ( long ) skip } , if possible ) to the end of the stream and return the total number
 * of bytes that were read .
 * < p > Note that for some sources that implement { @ link # sizeIfKnown } to provide a more efficient
 * implementation , it is < i > possible < / i > that this method will return a different number of bytes
 * than would be returned by reading all of the bytes ( for example , some special files may return
 * a size of 0 despite actually having content when read ) .
 * < p > In either case , for mutable sources such as files , a subsequent read may return a different
 * number of bytes if the contents are changed .
 * @ throws IOException if an I / O error occurs while reading the size of this source */
public long size ( ) throws IOException { } }

implementation:
Optional < Long > sizeIfKnown = sizeIfKnown ( ) ; if ( sizeIfKnown . isPresent ( ) ) { return sizeIfKnown . get ( ) ; } Closer closer = Closer . create ( ) ; try { InputStream in = closer . register ( openStream ( ) ) ; return countBySkipping ( in ) ; } catch ( IOException e ) { // skip may not be supported . . . at any rate , try reading
} finally { closer . close ( ) ; } closer = Closer . create ( ) ; try { InputStream in = closer . register ( openStream ( ) ) ; return ByteStreams . exhaust ( in ) ; } catch ( Throwable e ) { throw closer . rethrow ( e ) ; } finally { closer . close ( ) ; }


signature:
public class ByteSource { /** * Counts the bytes in the given input stream using skip if possible . Returns SKIP _ FAILED if the
 * first call to skip threw , in which case skip may just not be supported . */
private long countBySkipping ( InputStream in ) throws IOException { } }

implementation: long count = 0 ; long skipped ; while ( ( skipped = skipUpTo ( in , Integer . MAX_VALUE ) ) > 0 ) { count += skipped ; } return count ;


signature:
public class ByteSource { /** * Reads the full contents of this byte source as a byte array .
 * @ throws IOException if an I / O error occurs while reading from this source */
public byte [ ] read ( ) throws IOException { } }

implementation: Closer closer = Closer . create ( ) ; try { InputStream in = closer . register ( openStream ( ) ) ; Optional < Long > size = sizeIfKnown ( ) ; return size . isPresent ( ) ? ByteStreams . toByteArray ( in , size . get ( ) ) : ByteStreams . toByteArray ( in ) ; } catch ( Throwable e ) { throw closer . rethrow ( e ) ; } finally { closer . close ( ) ; }


signature:
public class ByteSource { /** * Reads the contents of this byte source using the given { @ code processor } to process bytes as
 * they are read . Stops when all bytes have been read or the consumer returns { @ code false } .
 * Returns the result produced by the processor .
 * @ throws IOException if an I / O error occurs while reading from this source or if { @ code
 * processor } throws an { @ code IOException }
 * @ since 16.0 */
@ Beta @ CanIgnoreReturnValue // some processors won ' t return a useful result
public < T > T read ( ByteProcessor < T > processor ) throws IOException { } }

implementation: checkNotNull ( processor ) ; Closer closer = Closer . create ( ) ; try { InputStream in = closer . register ( openStream ( ) ) ; return ByteStreams . readBytes ( in , processor ) ; } catch ( Throwable e ) { throw closer . rethrow ( e ) ; } finally { closer . close ( ) ; }


signature:
public class ByteSource { /** * Hashes the contents of this byte source using the given hash function .
 * @ throws IOException if an I / O error occurs while reading from this source */
public HashCode hash ( HashFunction hashFunction ) throws IOException { } }

implementation: Hasher hasher = hashFunction . newHasher ( ) ; copyTo ( Funnels . asOutputStream ( hasher ) ) ; return hasher . hash ( ) ;


signature:
public class ByteSource { /** * Checks that the contents of this byte source are equal to the contents of the given byte
 * source .
 * @ throws IOException if an I / O error occurs while reading from this source or { @ code other } */
public boolean contentEquals ( ByteSource other ) throws IOException { } }

implementation: checkNotNull ( other ) ; byte [ ] buf1 = createBuffer ( ) ; byte [ ] buf2 = createBuffer ( ) ; Closer closer = Closer . create ( ) ; try { InputStream in1 = closer . register ( openStream ( ) ) ; InputStream in2 = closer . register ( other . openStream ( ) ) ; while ( true ) { int read1 = ByteStreams . read ( in1 , buf1 , 0 , buf1 . length ) ; int read2 = ByteStreams . read ( in2 , buf2 , 0 , buf2 . length ) ; if ( read1 != read2 || ! Arrays . equals ( buf1 , buf2 ) ) { return false ; } else if ( read1 != buf1 . length ) { return true ; } } } catch ( Throwable e ) { throw closer . rethrow ( e ) ; } finally { closer . close ( ) ; }


signature:
public class ImmutableRangeMap { /** * Returns a { @ code Collector } that accumulates the input elements into a new { @ code
 * ImmutableRangeMap } . As in { @ link Builder } , overlapping ranges are not permitted .
 * @ since 23.1 */
public static < T , K extends Comparable < ? super K > , V > Collector < T , ? , ImmutableRangeMap < K , V > > toImmutableRangeMap ( Function < ? super T , Range < K > > keyFunction , Function < ? super T , ? extends V > valueFunction ) { } }

implementation: return CollectCollectors . toImmutableRangeMap ( keyFunction , valueFunction ) ;


signature:
public class ImmutableRangeMap { /** * Returns an empty immutable range map . */
@ SuppressWarnings ( "unchecked" ) public static < K extends Comparable < ? > , V > ImmutableRangeMap < K , V > of ( ) { } }

implementation: return ( ImmutableRangeMap < K , V > ) EMPTY ;


signature:
public class ImmutableRangeMap { /** * Returns an immutable range map mapping a single range to a single value . */
public static < K extends Comparable < ? > , V > ImmutableRangeMap < K , V > of ( Range < K > range , V value ) { } }

implementation: return new ImmutableRangeMap < > ( ImmutableList . of ( range ) , ImmutableList . of ( value ) ) ;


signature:
public class CompactLinkedHashSet { /** * Creates a < i > mutable < / i > { @ code CompactLinkedHashSet } instance containing the elements of the
 * given collection in the order returned by the collection ' s iterator .
 * @ param collection the elements that the set should contain
 * @ return a new { @ code CompactLinkedHashSet } containing those elements ( minus duplicates ) */
public static < E > CompactLinkedHashSet < E > create ( Collection < ? extends E > collection ) { } }

implementation: CompactLinkedHashSet < E > set = createWithExpectedSize ( collection . size ( ) ) ; set . addAll ( collection ) ; return set ;


signature:
public class CompactLinkedHashSet { /** * Creates a { @ code CompactLinkedHashSet } instance containing the given elements in unspecified
 * order .
 * @ param elements the elements that the set should contain
 * @ return a new { @ code CompactLinkedHashSet } containing those elements ( minus duplicates ) */
public static < E > CompactLinkedHashSet < E > create ( E ... elements ) { } }

implementation: CompactLinkedHashSet < E > set = createWithExpectedSize ( elements . length ) ; Collections . addAll ( set , elements ) ; return set ;


signature:
public class TreeTraverser { /** * Returns an unmodifiable iterable over the nodes in a tree structure , using post - order
 * traversal . That is , each node ' s subtrees are traversed before the node itself is returned .
 * < p > No guarantees are made about the behavior of the traversal when nodes change while iteration
 * is in progress or when the iterators generated by { @ link # children } are advanced .
 * @ deprecated Use { @ link com . google . common . graph . Traverser # depthFirstPostOrder } instead , which
 * has the same behavior . */
@ Deprecated public final FluentIterable < T > postOrderTraversal ( final T root ) { } }

implementation: checkNotNull ( root ) ; return new FluentIterable < T > ( ) { @ Override public UnmodifiableIterator < T > iterator ( ) { return postOrderIterator ( root ) ; } } ;


signature:
public class TreeBasedTable { /** * Creates an empty { @ code TreeBasedTable } that uses the natural orderings of both row and column
 * keys .
 * < p > The method signature specifies { @ code R extends Comparable } with a raw { @ link Comparable } ,
 * instead of { @ code R extends Comparable < ? super R > } , and the same for { @ code C } . That ' s
 * necessary to support classes defined without generics . */
public static < R extends Comparable , C extends Comparable , V > TreeBasedTable < R , C , V > create ( ) { } }

implementation: return new TreeBasedTable < > ( Ordering . natural ( ) , Ordering . natural ( ) ) ;


signature:
public class TreeBasedTable { /** * Creates an empty { @ code TreeBasedTable } that is ordered by the specified comparators .
 * @ param rowComparator the comparator that orders the row keys
 * @ param columnComparator the comparator that orders the column keys */
public static < R , C , V > TreeBasedTable < R , C , V > create ( Comparator < ? super R > rowComparator , Comparator < ? super C > columnComparator ) { } }

implementation: checkNotNull ( rowComparator ) ; checkNotNull ( columnComparator ) ; return new TreeBasedTable < > ( rowComparator , columnComparator ) ;


signature:
public class TreeBasedTable { /** * Creates a { @ code TreeBasedTable } with the same mappings and sort order as the specified { @ code
 * TreeBasedTable } . */
public static < R , C , V > TreeBasedTable < R , C , V > create ( TreeBasedTable < R , C , ? extends V > table ) { } }

implementation: TreeBasedTable < R , C , V > result = new TreeBasedTable < > ( table . rowComparator ( ) , table . columnComparator ( ) ) ; result . putAll ( table ) ; return result ;


signature:
public class TreeBasedTable { /** * Overridden column iterator to return columns values in globally sorted order . */
@ Override Iterator < C > createColumnKeyIterator ( ) { } }

implementation:
final Comparator < ? super C > comparator = columnComparator ( ) ; final Iterator < C > merged = Iterators . mergeSorted ( Iterables . transform ( backingMap . values ( ) , new Function < Map < C , V > , Iterator < C > > ( ) { @ Override public Iterator < C > apply ( Map < C , V > input ) { return input . keySet ( ) . iterator ( ) ; } } ) , comparator ) ; return new AbstractIterator < C > ( ) { @ NullableDecl C lastValue ; @ Override protected C computeNext ( ) { while ( merged . hasNext ( ) ) { C next = merged . next ( ) ; boolean duplicate = lastValue != null && comparator . compare ( next , lastValue ) == 0 ; // Keep looping till we find a non - duplicate value .
if ( ! duplicate ) { lastValue = next ; return lastValue ; } } lastValue = null ; // clear reference to unused data
return endOfData ( ) ; } } ;


signature:
public class Futures { /** * Creates a { @ code ListenableFuture } which has its value set immediately upon construction . The
 * getters just return the value . This { @ code Future } can ' t be canceled or timed out and its
 * { @ code isDone ( ) } method always returns { @ code true } . */
public static < V > ListenableFuture < V > immediateFuture ( @ Nullable V value ) { } }

implementation:
if ( value == null ) { // This cast is safe because null is assignable to V for all V ( i . e . it is covariant )
@ SuppressWarnings ( { "unchecked" , "rawtypes" } ) ListenableFuture < V > typedNull = ( ListenableFuture ) ImmediateSuccessfulFuture . NULL ; return typedNull ; } return new ImmediateSuccessfulFuture < V > ( value ) ;


signature:
public class Futures { /** * TODO ( b / 72241893 ) : Remove by 2019-01 */
@ Beta @ Deprecated @ GwtIncompatible // TODO
public static < V , X extends Exception > CheckedFuture < V , X > immediateCheckedFuture ( @ Nullable V value ) { } }

implementation: return new ImmediateSuccessfulCheckedFuture < > ( value ) ;


signature:
public class Futures { /** * Returns a { @ code ListenableFuture } which has an exception set immediately upon construction .
 * < p > The returned { @ code Future } can ' t be cancelled , and its { @ code isDone ( ) } method always
 * returns { @ code true } . Calling { @ code get ( ) } will immediately throw the provided { @ code
 * Throwable } wrapped in an { @ code ExecutionException } . */
public static < V > ListenableFuture < V > immediateFailedFuture ( Throwable throwable ) { } }

implementation: checkNotNull ( throwable ) ; return new ImmediateFailedFuture < V > ( throwable ) ;


signature:
public class Futures { /** * Executes { @ code callable } on the specified { @ code executor } , returning a { @ code Future } .
 * @ throws RejectedExecutionException if the task cannot be scheduled for execution
 * @ since 23.0 */
@ Beta public static < O > ListenableFuture < O > submitAsync ( AsyncCallable < O > callable , Executor executor ) { } }

implementation: TrustedListenableFutureTask < O > task = TrustedListenableFutureTask . create ( callable ) ; executor . execute ( task ) ; return task ;


signature:
public class Futures { /** * Schedules { @ code callable } on the specified { @ code executor } , returning a { @ code Future } .
 * @ throws RejectedExecutionException if the task cannot be scheduled for execution
 * @ since 23.0 */
@ Beta @ GwtIncompatible // java . util . concurrent . ScheduledExecutorService
@ SuppressWarnings ( "GoodTime" ) // should accept a java . time . Duration
public static < O > ListenableFuture < O > scheduleAsync ( AsyncCallable < O > callable , long delay , TimeUnit timeUnit , ScheduledExecutorService executorService ) { } }

implementation:
TrustedListenableFutureTask < O > task = TrustedListenableFutureTask . create ( callable ) ; final Future < ? > scheduled = executorService . schedule ( task , delay , timeUnit ) ; task . addListener ( new Runnable ( ) { @ Override public void run ( ) { // Don ' t want to interrupt twice
scheduled . cancel ( false ) ; } } , directExecutor ( ) ) ; return task ;


signature:
public class Futures { /** * Returns a { @ code Future } whose result is taken from the given primary { @ code input } or , if the
 * primary input fails with the given { @ code exceptionType } , from the result provided by the
 * { @ code fallback } . { @ link Function # apply } is not invoked until the primary input has failed , so
 * if the primary input succeeds , it is never invoked . If , during the invocation of { @ code
 * fallback } , an exception is thrown , this exception is used as the result of the output { @ code
 * Future } .
 * < p > Usage example :
 * < pre > { @ code
 * ListenableFuture < Integer > fetchCounterFuture = . . . ;
 * / / Falling back to a zero counter in case an exception happens when
 * / / processing the RPC to fetch counters .
 * ListenableFuture < Integer > faultTolerantFuture = Futures . catching (
 * fetchCounterFuture , FetchException . class , x - > 0 , directExecutor ( ) ) ;
 * } < / pre >
 * < p > When selecting an executor , note that { @ code directExecutor } is dangerous in some cases . See
 * the discussion in the { @ link ListenableFuture # addListener ListenableFuture . addListener }
 * documentation . All its warnings about heavyweight listeners are also applicable to heavyweight
 * functions passed to this method .
 * @ param input the primary input { @ code Future }
 * @ param exceptionType the exception type that triggers use of { @ code fallback } . The exception
 * type is matched against the input ' s exception . " The input ' s exception " means the cause of
 * the { @ link ExecutionException } thrown by { @ code input . get ( ) } or , if { @ code get ( ) } throws a
 * different kind of exception , that exception itself . To avoid hiding bugs and other
 * unrecoverable errors , callers should prefer more specific types , avoiding { @ code
 * Throwable . class } in particular .
 * @ param fallback the { @ link Function } to be called if { @ code input } fails with the expected
 * exception type . The function ' s argument is the input ' s exception . " The input ' s exception "
 * means the cause of the { @ link ExecutionException } thrown by { @ code input . get ( ) } or , if
 * { @ code get ( ) } throws a different kind of exception , that exception itself .
 * @ param executor the executor that runs { @ code fallback } if { @ code input } fails
 * @ since 19.0 */
@ Beta @ Partially . GwtIncompatible ( "AVAILABLE but requires exceptionType to be Throwable.class" ) public static < V , X extends Throwable > ListenableFuture < V > catching ( ListenableFuture < ? extends V > input , Class < X > exceptionType , Function < ? super X , ? extends V > fallback , Executor executor ) { } }

implementation: return AbstractCatchingFuture . create ( input , exceptionType , fallback , executor ) ;


signature:
public class Futures { /** * Returns a new { @ code Future } whose result is derived from the result of the given { @ code
 * Future } . If { @ code input } fails , the returned { @ code Future } fails with the same exception ( and
 * the function is not invoked ) . Example usage :
 * < pre > { @ code
 * ListenableFuture < QueryResult > queryFuture = . . . ;
 * ListenableFuture < List < Row > > rowsFuture =
 * transform ( queryFuture , QueryResult : : getRows , executor ) ;
 * } < / pre >
 * < p > When selecting an executor , note that { @ code directExecutor } is dangerous in some cases . See
 * the discussion in the { @ link ListenableFuture # addListener ListenableFuture . addListener }
 * documentation . All its warnings about heavyweight listeners are also applicable to heavyweight
 * functions passed to this method .
 * < p > The returned { @ code Future } attempts to keep its cancellation state in sync with that of the
 * input future . That is , if the returned { @ code Future } is cancelled , it will attempt to cancel
 * the input , and if the input is cancelled , the returned { @ code Future } will receive a callback
 * in which it will attempt to cancel itself .
 * < p > An example use of this method is to convert a serializable object returned from an RPC into
 * a POJO .
 * @ param input The future to transform
 * @ param function A Function to transform the results of the provided future to the results of
 * the returned future .
 * @ param executor Executor to run the function in .
 * @ return A future that holds result of the transformation .
 * @ since 9.0 ( in 2.0 as { @ code compose } ) */
@ Beta public static < I , O > ListenableFuture < O > transform ( ListenableFuture < I > input , Function < ? super I , ? extends O > function , Executor executor ) { } }

implementation: return AbstractTransformFuture . create ( input , function , executor ) ;


signature:
public class Futures { /** * Creates a new { @ code ListenableFuture } whose value is a list containing the values of all its
 * input futures , if all succeed .
 * < p > The list of results is in the same order as the input list .
 * < p > Canceling this future will attempt to cancel all the component futures , and if any of the
 * provided futures fails or is canceled , this one is , too .
 * @ param futures futures to combine
 * @ return a future that provides a list of the results of the component futures
 * @ since 10.0 */
@ Beta @ SafeVarargs public static < V > ListenableFuture < List < V > > allAsList ( ListenableFuture < ? extends V > ... futures ) { } }

implementation: return new ListFuture < V > ( ImmutableList . copyOf ( futures ) , true ) ;


signature:
public class Futures { /** * Creates a { @ link FutureCombiner } requiring that all passed in futures are successful .
 * < p > If any input fails , the returned future fails immediately .
 * @ since 20.0 */
@ Beta @ SafeVarargs public static < V > FutureCombiner < V > whenAllSucceed ( ListenableFuture < ? extends V > ... futures ) { } }

implementation: return new FutureCombiner < V > ( true , ImmutableList . copyOf ( futures ) ) ;


signature:
public class Futures { /** * Returns a { @ code ListenableFuture } whose result is set from the supplied future when it
 * completes . Cancelling the supplied future will also cancel the returned future , but cancelling
 * the returned future will have no effect on the supplied future .
 * @ since 15.0 */
@ Beta public static < V > ListenableFuture < V > nonCancellationPropagating ( ListenableFuture < V > future ) { } }

implementation: if ( future . isDone ( ) ) { return future ; } NonCancellationPropagatingFuture < V > output = new NonCancellationPropagatingFuture < > ( future ) ; future . addListener ( output , directExecutor ( ) ) ; return output ;


signature:
public class Futures { /** * Creates a new { @ code ListenableFuture } whose value is a list containing the values of all its
 * successful input futures . The list of results is in the same order as the input list , and if
 * any of the provided futures fails or is canceled , its corresponding position will contain
 * { @ code null } ( which is indistinguishable from the future having a successful value of { @ code
 * null } ) .
 * < p > Canceling this future will attempt to cancel all the component futures .
 * @ param futures futures to combine
 * @ return a future that provides a list of the results of the component futures
 * @ since 10.0 */
@ Beta public static < V > ListenableFuture < List < V > > successfulAsList ( Iterable < ? extends ListenableFuture < ? extends V > > futures ) { } }

implementation: return new ListFuture < V > ( ImmutableList . copyOf ( futures ) , false ) ;


signature:
public class Futures { /** * Returns a list of delegate futures that correspond to the futures received in the order that
 * they complete . Delegate futures return the same value or throw the same exception as the
 * corresponding input future returns / throws .
 * < p > " In the order that they complete " means , for practical purposes , about what you would
 * expect , but there are some subtleties . First , we do guarantee that , if the output future at
 * index n is done , the output future at index n - 1 is also done . ( But as usual with futures , some
 * listeners for future n may complete before some for future n - 1 . ) However , it is possible , if
 * one input completes with result X and another later with result Y , for Y to come before X in
 * the output future list . ( Such races are impossible to solve without global synchronization of
 * all future completions . And they should have little practical impact . )
 * < p > Cancelling a delegate future propagates to input futures once all the delegates complete ,
 * either from cancellation or because an input future has completed . If N futures are passed in ,
 * and M delegates are cancelled , the remaining M input futures will be cancelled once N - M of
 * the input futures complete . If all the delegates are cancelled , all the input futures will be
 * too .
 * @ since 17.0 */
@ Beta public static < T > ImmutableList < ListenableFuture < T > > inCompletionOrder ( Iterable < ? extends ListenableFuture < ? extends T > > futures ) { } }

implementation:
// Can ' t use Iterables . toArray because it ' s not gwt compatible
final Collection < ListenableFuture < ? extends T > > collection ; if ( futures instanceof Collection ) { collection = ( Collection < ListenableFuture < ? extends T > > ) futures ; } else { collection = ImmutableList . copyOf ( futures ) ; } @ SuppressWarnings ( "unchecked" ) ListenableFuture < ? extends T > [ ] copy = ( ListenableFuture < ? extends T > [ ] ) collection . toArray ( new ListenableFuture [ collection . size ( ) ] ) ; final InCompletionOrderState < T > state = new InCompletionOrderState < > ( copy ) ; ImmutableList . Builder < AbstractFuture < T > > delegatesBuilder = ImmutableList . builder ( ) ; for ( int i = 0 ; i < copy . length ; i ++ ) { delegatesBuilder . add ( new InCompletionOrderFuture < T > ( state ) ) ; } final ImmutableList < AbstractFuture < T > > delegates = delegatesBuilder . build ( ) ; for ( int i = 0 ; i < copy . length ; i ++ ) { final int localI = i ; copy [ i ] . addListener ( new Runnable ( ) { @ Override public void run ( ) { state . recordInputCompletion ( delegates , localI ) ; } } , directExecutor ( ) ) ; } @ SuppressWarnings ( "unchecked" ) ImmutableList < ListenableFuture < T > > delegatesCast = ( ImmutableList ) delegates ; return delegatesCast ;


signature:
public class Futures { /** * Registers separate success and failure callbacks to be run when the { @ code Future } ' s
 * computation is { @ linkplain java . util . concurrent . Future # isDone ( ) complete } or , if the
 * computation is already complete , immediately .
 * < p > The callback is run on { @ code executor } . There is no guaranteed ordering of execution of
 * callbacks , but any callback added through this method is guaranteed to be called once the
 * computation is complete .
 * < p > Example :
 * < pre > { @ code
 * ListenableFuture < QueryResult > future = . . . ;
 * Executor e = . . .
 * addCallback ( future ,
 * new FutureCallback < QueryResult > ( ) {
 * public void onSuccess ( QueryResult result ) {
 * storeInCache ( result ) ;
 * public void onFailure ( Throwable t ) {
 * reportError ( t ) ;
 * } < / pre >
 * < p > When selecting an executor , note that { @ code directExecutor } is dangerous in some cases . See
 * the discussion in the { @ link ListenableFuture # addListener ListenableFuture . addListener }
 * documentation . All its warnings about heavyweight listeners are also applicable to heavyweight
 * callbacks passed to this method .
 * < p > For a more general interface to attach a completion listener to a { @ code Future } , see { @ link
 * ListenableFuture # addListener addListener } .
 * @ param future The future attach the callback to .
 * @ param callback The callback to invoke when { @ code future } is completed .
 * @ param executor The executor to run { @ code callback } when the future completes .
 * @ since 10.0 */
public static < V > void addCallback ( final ListenableFuture < V > future , final FutureCallback < ? super V > callback , Executor executor ) { } }

implementation: Preconditions . checkNotNull ( callback ) ; future . addListener ( new CallbackListener < V > ( future , callback ) , executor ) ;


signature:
public class Futures { /** * Returns the result of the input { @ code Future } , which must have already completed .
 * < p > The benefits of this method are twofold . First , the name " getDone " suggests to readers that
 * the { @ code Future } is already done . Second , if buggy code calls { @ code getDone } on a { @ code
 * Future } that is still pending , the program will throw instead of block . This can be important
 * for APIs like { @ link # whenAllComplete whenAllComplete ( . . . ) } { @ code . } { @ link
 * FutureCombiner # call ( Callable , Executor ) call ( . . . ) } , where it is easy to use a new input from
 * the { @ code call } implementation but forget to add it to the arguments of { @ code
 * whenAllComplete } .
 * < p > If you are looking for a method to determine whether a given { @ code Future } is done , use the
 * instance method { @ link Future # isDone ( ) } .
 * @ throws ExecutionException if the { @ code Future } failed with an exception
 * @ throws CancellationException if the { @ code Future } was cancelled
 * @ throws IllegalStateException if the { @ code Future } is not done
 * @ since 20.0 */
@ CanIgnoreReturnValue // TODO ( cpovirk ) : Consider calling getDone ( ) in our own code .
public static < V > V getDone ( Future < V > future ) throws ExecutionException { } }

implementation:
/* * We throw IllegalStateException , since the call could succeed later . Perhaps we " should " throw
 * IllegalArgumentException , since the call could succeed with a different argument . Those
 * exceptions ' docs suggest that either is acceptable . Google ' s Java Practices page recommends
 * IllegalArgumentException here , in part to keep its recommendation simple : Static methods
 * should throw IllegalStateException only when they use static state .
 * Why do we deviate here ? The answer : We want for fluentFuture . getDone ( ) to throw the same
 * exception as Futures . getDone ( fluentFuture ) . */
checkState ( future . isDone ( ) , "Future was expected to be done: %s" , future ) ; return getUninterruptibly ( future ) ;