signature:
public class MediaType { /** * Parses a media type from its string representation .
 * @ throws IllegalArgumentException if the input is not parsable */
public static MediaType parse ( String input ) { } }

implementation: checkNotNull ( input ) ; Tokenizer tokenizer = new Tokenizer ( input ) ; try { String type = tokenizer . consumeToken ( TOKEN_MATCHER ) ; tokenizer . consumeCharacter ( '/' ) ; String subtype = tokenizer . consumeToken ( TOKEN_MATCHER ) ; ImmutableListMultimap . Builder < String , String > parameters = ImmutableListMultimap . builder ( ) ; while ( tokenizer . hasMore ( ) ) { tokenizer . consumeTokenIfPresent ( LINEAR_WHITE_SPACE ) ; tokenizer . consumeCharacter ( ';' ) ; tokenizer . consumeTokenIfPresent ( LINEAR_WHITE_SPACE ) ; String attribute = tokenizer . consumeToken ( TOKEN_MATCHER ) ; tokenizer . consumeCharacter ( '=' ) ; final String value ; if ( '"' == tokenizer . previewChar ( ) ) { tokenizer . consumeCharacter ( '"' ) ; StringBuilder valueBuilder = new StringBuilder ( ) ; while ( '"' != tokenizer . previewChar ( ) ) { if ( '\\' == tokenizer . previewChar ( ) ) { tokenizer . consumeCharacter ( '\\' ) ; valueBuilder . append ( tokenizer . consumeCharacter ( ascii ( ) ) ) ; } else { valueBuilder . append ( tokenizer . consumeToken ( QUOTED_TEXT_MATCHER ) ) ; } } value = valueBuilder . toString ( ) ; tokenizer . consumeCharacter ( '"' ) ; } else { value = tokenizer . consumeToken ( TOKEN_MATCHER ) ; } parameters . put ( attribute , value ) ; } return create ( type , subtype , parameters . build ( ) ) ; } catch ( IllegalStateException e ) { throw new IllegalArgumentException ( "Could not parse '" + input + "'" , e ) ; }


signature:
public class Iterators { /** * Returns the number of elements in the specified iterator that equal the specified object . The
 * iterator will be left exhausted : its { @ code hasNext ( ) } method will return { @ code false } .
 * @ see Collections # frequency */
public static int frequency ( Iterator < ? > iterator , @ Nullable Object element ) { } }

implementation:
int count = 0 ; while ( contains ( iterator , element ) ) { // Since it lives in the same class , we know contains gets to the element and then stops ,
// though that isn ' t currently publicly documented .
count ++ ; } return count ;


signature:
public class Iterators { /** * Advances { @ code iterator } { @ code position + 1 } times , returning the element at the { @ code
 * position } th position or { @ code defaultValue } otherwise .
 * @ param position position of the element to return
 * @ param defaultValue the default value to return if the iterator is empty or if { @ code position }
 * is greater than the number of elements remaining in { @ code iterator }
 * @ return the element at the specified position in { @ code iterator } or { @ code defaultValue } if
 * { @ code iterator } produces fewer than { @ code position + 1 } elements .
 * @ throws IndexOutOfBoundsException if { @ code position } is negative
 * @ since 4.0 */
public static < T > @ Nullable T get ( Iterator < ? extends T > iterator , int position , @ Nullable T defaultValue ) { } }

implementation: checkNonnegative ( position ) ; advance ( iterator , position ) ; return getNext ( iterator , defaultValue ) ;


signature:
public class Iterators { /** * Returns the next element in { @ code iterator } or { @ code defaultValue } if the iterator is empty .
 * The { @ link Iterables } analog to this method is { @ link Iterables # getFirst } .
 * @ param defaultValue the default value to return if the iterator is empty
 * @ return the next element of { @ code iterator } or the default value
 * @ since 7.0 */
public static < T > @ Nullable T getNext ( Iterator < ? extends T > iterator , @ Nullable T defaultValue ) { } }

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


signature:
public class Iterators { /** * Advances { @ code iterator } to the end , returning the last element or { @ code defaultValue } if the
 * iterator is empty .
 * @ param defaultValue the default value to return if the iterator is empty
 * @ return the last element of { @ code iterator }
 * @ since 3.0 */
public static < T > @ Nullable T getLast ( Iterator < ? extends T > iterator , @ Nullable T defaultValue ) { } }

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


signature:
public class Iterators { /** * Returns an iterator containing only { @ code value } .
 * < p > The { @ link Iterable } equivalent of this method is { @ link Collections # singleton } . */
public static < T > UnmodifiableIterator < T > singletonIterator ( final @ Nullable T value ) { } }

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


signature:
public class TypeCapture { /** * Returns the captured type . */
final Type capture ( ) { } }

implementation: Type superclass = getClass ( ) . getGenericSuperclass ( ) ; checkArgument ( superclass instanceof ParameterizedType , "%s isn't parameterized" , superclass ) ; return ( ( ParameterizedType ) superclass ) . getActualTypeArguments ( ) [ 0 ] ;


signature:
public class LinkedHashMultimap { /** * Constructs an empty { @ code LinkedHashMultimap } with enough capacity to hold the specified
 * numbers of keys and values without rehashing .
 * @ param expectedKeys the expected number of distinct keys
 * @ param expectedValuesPerKey the expected average number of values per key
 * @ throws IllegalArgumentException if { @ code expectedKeys } or { @ code expectedValuesPerKey } is
 * negative */
public static < K , V > LinkedHashMultimap < K , V > create ( int expectedKeys , int expectedValuesPerKey ) { } }

implementation: return new LinkedHashMultimap < > ( Maps . capacity ( expectedKeys ) , Maps . capacity ( expectedValuesPerKey ) ) ;


signature:
public class LinkedHashMultimap { /** * Constructs a { @ code LinkedHashMultimap } 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 . The new multimap has the same { @ link Multimap # entries ( ) } iteration order
 * as the input multimap , except for excluding duplicate mappings .
 * @ param multimap the multimap whose contents are copied to this multimap */
public static < K , V > LinkedHashMultimap < K , V > create ( Multimap < ? extends K , ? extends V > multimap ) { } }

implementation: LinkedHashMultimap < K , V > result = create ( multimap . keySet ( ) . size ( ) , DEFAULT_VALUE_SET_CAPACITY ) ; result . putAll ( multimap ) ; return result ;


signature:
public class LinkedHashMultimap { /** * { @ inheritDoc }
 * < p > If { @ code values } is not empty and the multimap already contains a mapping for { @ code key } ,
 * the { @ code keySet ( ) } ordering is unchanged . However , the provided values always come last in
 * the { @ link # entries ( ) } and { @ link # values ( ) } iteration orderings . */
@ CanIgnoreReturnValue @ Override public Set < V > replaceValues ( @ NullableDecl K key , Iterable < ? extends V > values ) { } }

implementation: return super . replaceValues ( key , values ) ;


signature:
public class CacheLoader { /** * Computes or retrieves a replacement value corresponding to an already - cached { @ code key } . This
 * method is called when an existing cache entry is refreshed by { @ link
 * CacheBuilder # refreshAfterWrite } , or through a call to { @ link LoadingCache # refresh } .
 * < p > This implementation synchronously delegates to { @ link # load } . It is recommended that it be
 * overridden with an asynchronous implementation when using { @ link
 * CacheBuilder # refreshAfterWrite } .
 * < p > < b > Note : < / b > < i > all exceptions thrown by this method will be logged and then swallowed < / i > .
 * @ param key the non - null key whose value should be loaded
 * @ param oldValue the non - null old value corresponding to { @ code key }
 * @ return the future new value associated with { @ code key } ; < b > must not be null , must not return
 * null < / b >
 * @ throws Exception if unable to reload the result
 * @ throws InterruptedException if this method is interrupted . { @ code InterruptedException } is
 * treated like any other { @ code Exception } in all respects except that , when it is caught ,
 * the thread ' s interrupt status is set
 * @ since 11.0 */
@ GwtIncompatible // Futures
public ListenableFuture < V > reload ( K key , V oldValue ) throws Exception { } }

implementation: checkNotNull ( key ) ; checkNotNull ( oldValue ) ; return Futures . immediateFuture ( load ( key ) ) ;


signature:
public class CacheLoader { /** * Returns a cache loader that uses { @ code function } to load keys , and without supporting either
 * reloading or bulk loading . This is most useful when you can pass a lambda expression . Otherwise
 * it is useful mostly when you already have an existing function instance .
 * @ param function the function to be used for loading values ; must never return { @ code null }
 * @ return a cache loader that loads values by passing each key to { @ code function } */
public static < K , V > CacheLoader < K , V > from ( Function < K , V > function ) { } }

implementation: return new FunctionToCacheLoader < > ( function ) ;


signature:
public class CacheLoader { /** * Returns a cache loader based on an < i > existing < / i > supplier instance . Note that there ' s no need
 * to create a < i > new < / i > supplier just to pass it in here ; just subclass { @ code CacheLoader } and
 * implement { @ link # load load } instead .
 * @ param supplier the supplier to be used for loading values ; must never return { @ code null }
 * @ return a cache loader that loads values by calling { @ link Supplier # get } , irrespective of the
 * key */
public static < V > CacheLoader < Object , V > from ( Supplier < V > supplier ) { } }

implementation: return new SupplierToCacheLoader < V > ( supplier ) ;


signature:
public class CacheLoader { /** * Returns a { @ code CacheLoader } which wraps { @ code loader } , executing calls to { @ link
 * CacheLoader # reload } using { @ code executor } .
 * < p > This method is useful only when { @ code loader . reload } has a synchronous implementation , such
 * as { @ linkplain # reload the default implementation } .
 * @ since 17.0 */
@ GwtIncompatible // Executor + Futures
public static < K , V > CacheLoader < K , V > asyncReloading ( final CacheLoader < K , V > loader , final Executor executor ) { } }

implementation: checkNotNull ( loader ) ; checkNotNull ( executor ) ; return new CacheLoader < K , V > ( ) { @ Override public V load ( K key ) throws Exception { return loader . load ( key ) ; } @ Override public ListenableFuture < V > reload ( final K key , final V oldValue ) throws Exception { ListenableFutureTask < V > task = ListenableFutureTask . create ( new Callable < V > ( ) { @ Override public V call ( ) throws Exception { return loader . reload ( key , oldValue ) . get ( ) ; } } ) ; executor . execute ( task ) ; return task ; } @ Override public Map < K , V > loadAll ( Iterable < ? extends K > keys ) throws Exception { return loader . loadAll ( keys ) ; } } ;


signature:
public class IntMath { /** * Returns the smallest power of two greater than or equal to { @ code x } . This is equivalent to
 * { @ code checkedPow ( 2 , log2 ( x , CEILING ) ) } .
 * @ throws IllegalArgumentException if { @ code x < = 0}
 * @ throws ArithmeticException of the next - higher power of two is not representable as an { @ code
 * int } , i . e . when { @ code x > 2 ^ 30}
 * @ since 20.0 */
@ Beta public static int ceilingPowerOfTwo ( int x ) { } }

implementation: checkPositive ( "x" , x ) ; if ( x > MAX_SIGNED_POWER_OF_TWO ) { throw new ArithmeticException ( "ceilingPowerOfTwo(" + x + ") not representable as an int" ) ; } return 1 << - Integer . numberOfLeadingZeros ( x - 1 ) ;


signature:
public class IntMath { /** * Returns the base - 2 logarithm of { @ code x } , rounded according to the specified rounding mode .
 * @ throws IllegalArgumentException if { @ code x < = 0}
 * @ throws ArithmeticException if { @ code mode } is { @ link RoundingMode # UNNECESSARY } and { @ code x }
 * is not a power of two */
@ SuppressWarnings ( "fallthrough" ) // TODO ( kevinb ) : remove after this warning is disabled globally
public static int log2 ( int x , RoundingMode mode ) { } }

implementation:
checkPositive ( "x" , x ) ; switch ( mode ) { case UNNECESSARY : checkRoundingUnnecessary ( isPowerOfTwo ( x ) ) ; // fall through
case DOWN : case FLOOR : return ( Integer . SIZE - 1 ) - Integer . numberOfLeadingZeros ( x ) ; case UP : case CEILING : return Integer . SIZE - Integer . numberOfLeadingZeros ( x - 1 ) ; case HALF_DOWN : case HALF_UP : case HALF_EVEN : // Since sqrt ( 2 ) is irrational , log2 ( x ) - logFloor cannot be exactly 0.5
int leadingZeros = Integer . numberOfLeadingZeros ( x ) ; int cmp = MAX_POWER_OF_SQRT2_UNSIGNED >>> leadingZeros ; // floor ( 2 ^ ( logFloor + 0.5 ) )
int logFloor = ( Integer . SIZE - 1 ) - leadingZeros ; return logFloor + lessThanBranchFree ( cmp , x ) ; default : throw new AssertionError ( ) ; }


signature:
public class IntMath { /** * Returns the square root of { @ code x } , rounded with the specified rounding mode .
 * @ throws IllegalArgumentException if { @ code x < 0}
 * @ throws ArithmeticException if { @ code mode } is { @ link RoundingMode # UNNECESSARY } and { @ code
 * sqrt ( x ) } is not an integer */
@ GwtIncompatible // need BigIntegerMath to adequately test
@ SuppressWarnings ( "fallthrough" ) public static int sqrt ( int x , RoundingMode mode ) { } }

implementation:
checkNonNegative ( "x" , x ) ; int sqrtFloor = sqrtFloor ( x ) ; switch ( mode ) { case UNNECESSARY : checkRoundingUnnecessary ( sqrtFloor * sqrtFloor == x ) ; // fall through
case FLOOR : case DOWN : return sqrtFloor ; case CEILING : case UP : return sqrtFloor + lessThanBranchFree ( sqrtFloor * sqrtFloor , x ) ; case HALF_DOWN : case HALF_UP : case HALF_EVEN : int halfSquare = sqrtFloor * sqrtFloor + sqrtFloor ; /* * We wish to test whether or not x < = ( sqrtFloor + 0.5 ) ^ 2 = halfSquare + 0.25 . Since both x
 * and halfSquare are integers , this is equivalent to testing whether or not x < =
 * halfSquare . ( We have to deal with overflow , though . )
 * If we treat halfSquare as an unsigned int , we know that
 * sqrtFloor ^ 2 < = x < ( sqrtFloor + 1 ) ^ 2
 * halfSquare - sqrtFloor < = x < halfSquare + sqrtFloor + 1
 * so | x - halfSquare | < = sqrtFloor . Therefore , it ' s safe to treat x - halfSquare as a
 * signed int , so lessThanBranchFree is safe for use . */
return sqrtFloor + lessThanBranchFree ( halfSquare , x ) ; default : throw new AssertionError ( ) ; }


signature:
public class IntMath { /** * Returns { @ code x mod m } , a non - negative value less than { @ code m } . This differs from { @ code x %
 * m } , which might be negative .
 * < p > For example :
 * < pre > { @ code
 * mod ( 7 , 4 ) = = 3
 * mod ( - 7 , 4 ) = = 1
 * mod ( - 1 , 4 ) = = 3
 * mod ( - 8 , 4 ) = = 0
 * mod ( 8 , 4 ) = = 0
 * } < / pre >
 * @ throws ArithmeticException if { @ code m < = 0}
 * @ see < a href = " http : / / docs . oracle . com / javase / specs / jls / se7 / html / jls - 15 . html # jls - 15.17.3 " >
 * Remainder Operator < / a > */
public static int mod ( int x , int m ) { } }

implementation: if ( m <= 0 ) { throw new ArithmeticException ( "Modulus " + m + " must be > 0" ) ; } int result = x % m ; return ( result >= 0 ) ? result : result + m ;


signature:
public class IntMath { /** * Returns the { @ code b } to the { @ code k } th power , provided it does not overflow .
 * < p > { @ link # pow } may be faster , but does not check for overflow .
 * @ throws ArithmeticException if { @ code b } to the { @ code k } th power overflows in signed { @ code
 * int } arithmetic */
public static int checkedPow ( int b , int k ) { } }

implementation:
checkNonNegative ( "exponent" , k ) ; switch ( b ) { case 0 : return ( k == 0 ) ? 1 : 0 ; case 1 : return 1 ; case ( - 1 ) : return ( ( k & 1 ) == 0 ) ? 1 : - 1 ; case 2 : checkNoOverflow ( k < Integer . SIZE - 1 , "checkedPow" , b , k ) ; return 1 << k ; case ( - 2 ) : checkNoOverflow ( k < Integer . SIZE , "checkedPow" , b , k ) ; return ( ( k & 1 ) == 0 ) ? 1 << k : - 1 << k ; default : // continue below to handle the general case
} int accum = 1 ; while ( true ) { switch ( k ) { case 0 : return accum ; case 1 : return checkedMultiply ( accum , b ) ; default : if ( ( k & 1 ) != 0 ) { accum = checkedMultiply ( accum , b ) ; } k >>= 1 ; if ( k > 0 ) { checkNoOverflow ( - FLOOR_SQRT_MAX_INT <= b & b <= FLOOR_SQRT_MAX_INT , "checkedPow" , b , k ) ; b *= b ; } } }


signature:
public class IntMath { /** * Returns { @ code n ! } , that is , the product of the first { @ code n } positive integers , { @ code 1 } if
 * { @ code n = = 0 } , or { @ link Integer # MAX _ VALUE } if the result does not fit in a { @ code int } .
 * @ throws IllegalArgumentException if { @ code n < 0} */
public static int factorial ( int n ) { } }

implementation: checkNonNegative ( "n" , n ) ; return ( n < factorials . length ) ? factorials [ n ] : Integer . MAX_VALUE ;


signature:
public class Sets { /** * http : / / code . google . com / p / google - web - toolkit / issues / detail ? id = 3028 */
@ GwtCompatible ( serializable = true ) public static < E extends Enum < E > > ImmutableSet < E > immutableEnumSet ( E anElement , E ... otherElements ) { } }

implementation: return ImmutableEnumSet . asImmutable ( EnumSet . of ( anElement , otherElements ) ) ;


signature:
public class Sets { /** * http : / / code . google . com / p / google - web - toolkit / issues / detail ? id = 3028 */
@ GwtCompatible ( serializable = true ) public static < E extends Enum < E > > ImmutableSet < E > immutableEnumSet ( Iterable < E > elements ) { } }

implementation: if ( elements instanceof ImmutableEnumSet ) { return ( ImmutableEnumSet < E > ) elements ; } else if ( elements instanceof Collection ) { Collection < E > collection = ( Collection < E > ) elements ; if ( collection . isEmpty ( ) ) { return ImmutableSet . of ( ) ; } else { return ImmutableEnumSet . asImmutable ( EnumSet . copyOf ( collection ) ) ; } } else { Iterator < E > itr = elements . iterator ( ) ; if ( itr . hasNext ( ) ) { EnumSet < E > enumSet = EnumSet . of ( itr . next ( ) ) ; Iterators . addAll ( enumSet , itr ) ; return ImmutableEnumSet . asImmutable ( enumSet ) ; } else { return ImmutableSet . of ( ) ; } }


signature:
public class Sets { /** * Returns a new , < i > mutable < / i > { @ code EnumSet } instance containing the given elements in their
 * natural order . This method behaves identically to { @ link EnumSet # copyOf ( Collection ) } , but also
 * accepts non - { @ code Collection } iterables and empty iterables . */
public static < E extends Enum < E > > EnumSet < E > newEnumSet ( Iterable < E > iterable , Class < E > elementType ) { } }

implementation: EnumSet < E > set = EnumSet . noneOf ( elementType ) ; Iterables . addAll ( set , iterable ) ; return set ;


signature:
public class Sets { /** * Creates a < i > mutable < / i > { @ code HashSet } instance containing the given elements . A very thin
 * convenience for creating an empty set then calling { @ link Collection # addAll } or { @ link
 * Iterables # addAll } .
 * < p > < b > Note : < / b > if mutability is not required and the elements are non - null , use { @ link
 * ImmutableSet # copyOf ( Iterable ) } instead . ( Or , change { @ code elements } to be a { @ link
 * FluentIterable } and call { @ code elements . toSet ( ) } . )
 * < p > < b > Note : < / b > if { @ code E } is an { @ link Enum } type , use { @ link # newEnumSet ( Iterable , Class ) }
 * instead .
 * < p > < b > Note for Java 7 and later : < / b > if { @ code elements } is a { @ link Collection } , you don ' t
 * need this method . Instead , use the { @ code HashSet } constructor directly , taking advantage of
 * the new < a href = " http : / / goo . gl / iz2Wi " > " diamond " syntax < / a > .
 * < p > Overall , this method is not very useful and will likely be deprecated in the future . */
public static < E > HashSet < E > newHashSet ( Iterable < ? extends E > elements ) { } }

implementation: return ( elements instanceof Collection ) ? new HashSet < E > ( Collections2 . cast ( elements ) ) : newHashSet ( elements . iterator ( ) ) ;


signature:
public class Sets { /** * Creates a < i > mutable < / i > { @ code HashSet } instance containing the given elements . A very thin
 * convenience for creating an empty set and then calling { @ link Iterators # addAll } .
 * < p > < b > Note : < / b > if mutability is not required and the elements are non - null , use { @ link
 * ImmutableSet # copyOf ( Iterator ) } instead .
 * < p > < b > Note : < / b > if { @ code E } is an { @ link Enum } type , you should create an { @ link EnumSet }
 * instead .
 * < p > Overall , this method is not very useful and will likely be deprecated in the future . */
public static < E > HashSet < E > newHashSet ( Iterator < ? extends E > elements ) { } }

implementation: HashSet < E > set = newHashSet ( ) ; Iterators . addAll ( set , elements ) ; return set ;


signature:
public class Sets { /** * Returns a new hash set using the smallest initial table size that can hold { @ code expectedSize }
 * elements without resizing . Note that this is not what { @ link HashSet # HashSet ( int ) } does , but it
 * is what most users want and expect it to do .
 * < p > This behavior can ' t be broadly guaranteed , but has been tested with OpenJDK 1.7 and 1.8.
 * @ param expectedSize the number of elements you expect to add to the returned set
 * @ return a new , empty hash set with enough capacity to hold { @ code expectedSize } elements
 * without resizing
 * @ throws IllegalArgumentException if { @ code expectedSize } is negative */
public static < E > HashSet < E > newHashSetWithExpectedSize ( int expectedSize ) { } }

implementation: return new HashSet < E > ( Maps . capacity ( expectedSize ) ) ;


signature:
public class Sets { /** * Creates a thread - safe set backed by a hash map and containing the given elements . The set is
 * backed by a { @ link ConcurrentHashMap } instance , and thus carries the same concurrency
 * guarantees .
 * < p > Unlike { @ code HashSet } , this class does NOT allow { @ code null } to be used as an element . The
 * set is serializable .
 * @ param elements the elements that the set should contain
 * @ return a new thread - safe set containing those elements ( minus duplicates )
 * @ throws NullPointerException if { @ code elements } or any of its contents is null
 * @ since 15.0 */
public static < E > Set < E > newConcurrentHashSet ( Iterable < ? extends E > elements ) { } }

implementation: Set < E > set = newConcurrentHashSet ( ) ; Iterables . addAll ( set , elements ) ; return set ;


signature:
public class Sets { /** * Creates a < i > mutable < / i > { @ code LinkedHashSet } instance containing the given elements in order .
 * < p > < b > Note : < / b > if mutability is not required and the elements are non - null , use { @ link
 * ImmutableSet # copyOf ( Iterable ) } instead .
 * < p > < b > Note for Java 7 and later : < / b > if { @ code elements } is a { @ link Collection } , you don ' t
 * need this method . Instead , use the { @ code LinkedHashSet } constructor directly , taking advantage
 * of the new < a href = " http : / / goo . gl / iz2Wi " > " diamond " syntax < / a > .
 * < p > Overall , this method is not very useful and will likely be deprecated in the future .
 * @ param elements the elements that the set should contain , in order
 * @ return a new { @ code LinkedHashSet } containing those elements ( minus duplicates ) */
public static < E > LinkedHashSet < E > newLinkedHashSet ( Iterable < ? extends E > elements ) { } }

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


signature:
public class Sets { /** * Creates a { @ code LinkedHashSet } instance , with a high enough " initial capacity " that it
 * < i > should < / i > hold { @ code expectedSize } elements without growth . This behavior cannot be
 * broadly guaranteed , but it is observed to be true for OpenJDK 1.7 . It also can ' t be guaranteed
 * that the method isn ' t inadvertently < i > oversizing < / i > the returned set .
 * @ param expectedSize the number of elements you expect to add to the returned set
 * @ return a new , empty { @ code LinkedHashSet } with enough capacity to hold { @ code expectedSize }
 * elements without resizing
 * @ throws IllegalArgumentException if { @ code expectedSize } is negative
 * @ since 11.0 */
public static < E > LinkedHashSet < E > newLinkedHashSetWithExpectedSize ( int expectedSize ) { } }

implementation: return new LinkedHashSet < E > ( Maps . capacity ( expectedSize ) ) ;


signature:
public class Sets { /** * Creates a < i > mutable < / i > { @ code TreeSet } instance containing the given elements sorted by their
 * natural ordering .
 * < p > < b > Note : < / b > if mutability is not required , use { @ link ImmutableSortedSet # copyOf ( Iterable ) }
 * instead .
 * < p > < b > Note : < / b > If { @ code elements } is a { @ code SortedSet } with an explicit comparator , this
 * method has different behavior than { @ link TreeSet # TreeSet ( SortedSet ) } , which returns a { @ code
 * TreeSet } with that comparator .
 * < p > < b > Note for Java 7 and later : < / b > this method is now unnecessary and should be treated as
 * deprecated . Instead , use the { @ code TreeSet } constructor directly , taking advantage of the new
 * < a href = " http : / / goo . gl / iz2Wi " > " diamond " syntax < / a > .
 * < p > This method is just a small convenience for creating an empty set and then calling { @ link
 * Iterables # addAll } . This method is not very useful and will likely be deprecated in the future .
 * @ param elements the elements that the set should contain
 * @ return a new { @ code TreeSet } containing those elements ( minus duplicates ) */
public static < E extends Comparable > TreeSet < E > newTreeSet ( Iterable < ? extends E > elements ) { } }

implementation: TreeSet < E > set = newTreeSet ( ) ; Iterables . addAll ( set , elements ) ; return set ;


signature:
public class Sets { /** * Creates a < i > mutable < / i > , empty { @ code TreeSet } instance with the given comparator .
 * < p > < b > Note : < / b > if mutability is not required , use { @ code
 * ImmutableSortedSet . orderedBy ( comparator ) . build ( ) } instead .
 * < p > < b > Note for Java 7 and later : < / b > this method is now unnecessary and should be treated as
 * deprecated . Instead , use the { @ code TreeSet } constructor directly , taking advantage of the new
 * < a href = " http : / / goo . gl / iz2Wi " > " diamond " syntax < / a > . One caveat to this is that the { @ code
 * TreeSet } constructor uses a null { @ code Comparator } to mean " natural ordering , " whereas this
 * factory rejects null . Clean your code accordingly .
 * @ param comparator the comparator to use to sort the set
 * @ return a new , empty { @ code TreeSet }
 * @ throws NullPointerException if { @ code comparator } is null */
public static < E > TreeSet < E > newTreeSet ( Comparator < ? super E > comparator ) { } }

implementation: return new TreeSet < E > ( checkNotNull ( comparator ) ) ;


signature:
public class Sets { /** * Creates an empty { @ code Set } that uses identity to determine equality . It compares object
 * references , instead of calling { @ code equals } , to determine whether a provided object matches
 * an element in the set . For example , { @ code contains } returns { @ code false } when passed an
 * object that equals a set member , but isn ' t the same instance . This behavior is similar to the
 * way { @ code IdentityHashMap } handles key lookups .
 * @ since 8.0 */
public static < E > Set < E > newIdentityHashSet ( ) { } }

implementation: return Collections . newSetFromMap ( Maps . < E , Boolean > newIdentityHashMap ( ) ) ;


signature:
public class Sets { /** * Creates a { @ code CopyOnWriteArraySet } instance containing the given elements .
 * @ param elements the elements that the set should contain , in order
 * @ return a new { @ code CopyOnWriteArraySet } containing those elements
 * @ since 12.0 */
@ GwtIncompatible // CopyOnWriteArraySet
public static < E > CopyOnWriteArraySet < E > newCopyOnWriteArraySet ( Iterable < ? extends E > elements ) { } }

implementation:
// We copy elements to an ArrayList first , rather than incurring the
// quadratic cost of adding them to the COWAS directly .
Collection < ? extends E > elementsCollection = ( elements instanceof Collection ) ? Collections2 . cast ( elements ) : Lists . newArrayList ( elements ) ; return new CopyOnWriteArraySet < E > ( elementsCollection ) ;


signature:
public class Sets { /** * Creates an { @ code EnumSet } consisting of all enum values that are not in the specified
 * collection . If the collection is an { @ link EnumSet } , this method has the same behavior as
 * { @ link EnumSet # complementOf } . Otherwise , the specified collection must contain at least one
 * element , in order to determine the element type . If the collection could be empty , use { @ link
 * # complementOf ( Collection , Class ) } instead of this method .
 * @ param collection the collection whose complement should be stored in the enum set
 * @ return a new , modifiable { @ code EnumSet } containing all values of the enum that aren ' t present
 * in the given collection
 * @ throws IllegalArgumentException if { @ code collection } is not an { @ code EnumSet } instance and
 * contains no elements */
public static < E extends Enum < E > > EnumSet < E > complementOf ( Collection < E > collection ) { } }

implementation: if ( collection instanceof EnumSet ) { return EnumSet . complementOf ( ( EnumSet < E > ) collection ) ; } checkArgument ( ! collection . isEmpty ( ) , "collection is empty; use the other version of this method" ) ; Class < E > type = collection . iterator ( ) . next ( ) . getDeclaringClass ( ) ; return makeComplementByHand ( collection , type ) ;


signature:
public class Sets { /** * Creates an { @ code EnumSet } consisting of all enum values that are not in the specified
 * collection . This is equivalent to { @ link EnumSet # complementOf } , but can act on any input
 * collection , as long as the elements are of enum type .
 * @ param collection the collection whose complement should be stored in the { @ code EnumSet }
 * @ param type the type of the elements in the set
 * @ return a new , modifiable { @ code EnumSet } initially containing all the values of the enum not
 * present in the given collection */
public static < E extends Enum < E > > EnumSet < E > complementOf ( Collection < E > collection , Class < E > type ) { } }

implementation: checkNotNull ( collection ) ; return ( collection instanceof EnumSet ) ? EnumSet . complementOf ( ( EnumSet < E > ) collection ) : makeComplementByHand ( collection , type ) ;


signature:
public class Sets { /** * Returns an unmodifiable < b > view < / b > of the union of two sets . The returned set contains all
 * elements that are contained in either backing set . Iterating over the returned set iterates
 * first over all the elements of { @ code set1 } , then over each element of { @ code set2 } , in order ,
 * that is not contained in { @ code set1 } .
 * < p > Results are undefined if { @ code set1 } and { @ code set2 } are sets based on different
 * equivalence relations ( as { @ link HashSet } , { @ link TreeSet } , and the { @ link Map # keySet } of an
 * { @ code IdentityHashMap } all are ) . */
public static < E > SetView < E > union ( final Set < ? extends E > set1 , final Set < ? extends E > set2 ) { } }

implementation: checkNotNull ( set1 , "set1" ) ; checkNotNull ( set2 , "set2" ) ; return new SetView < E > ( ) { @ Override public int size ( ) { int size = set1 . size ( ) ; for ( E e : set2 ) { if ( ! set1 . contains ( e ) ) { size ++ ; } } return size ; } @ Override public boolean isEmpty ( ) { return set1 . isEmpty ( ) && set2 . isEmpty ( ) ; } @ Override public UnmodifiableIterator < E > iterator ( ) { return new AbstractIterator < E > ( ) { final Iterator < ? extends E > itr1 = set1 . iterator ( ) ; final Iterator < ? extends E > itr2 = set2 . iterator ( ) ; @ Override protected E computeNext ( ) { if ( itr1 . hasNext ( ) ) { return itr1 . next ( ) ; } while ( itr2 . hasNext ( ) ) { E e = itr2 . next ( ) ; if ( ! set1 . contains ( e ) ) { return e ; } } return endOfData ( ) ; } } ; } @ Override public boolean contains ( Object object ) { return set1 . contains ( object ) || set2 . contains ( object ) ; } @ Override public < S extends Set < E > > S copyInto ( S set ) { set . addAll ( set1 ) ; set . addAll ( set2 ) ; return set ; } @ Override public ImmutableSet < E > immutableCopy ( ) { return new ImmutableSet . Builder < E > ( ) . addAll ( set1 ) . addAll ( set2 ) . build ( ) ; } } ;


signature:
public class Sets { /** * Returns an unmodifiable < b > view < / b > of the intersection of two sets . The returned set contains
 * all elements that are contained by both backing sets . The iteration order of the returned set
 * matches that of { @ code set1 } .
 * < p > Results are undefined if { @ code set1 } and { @ code set2 } are sets based on different
 * equivalence relations ( as { @ code HashSet } , { @ code TreeSet } , and the keySet of an { @ code
 * IdentityHashMap } all are ) .
 * < p > < b > Note : < / b > The returned view performs slightly better when { @ code set1 } is the smaller of
 * the two sets . If you have reason to believe one of your sets will generally be smaller than the
 * other , pass it first . Unfortunately , since this method sets the generic type of the returned
 * set based on the type of the first set passed , this could in rare cases force you to make a
 * cast , for example :
 * < pre > { @ code
 * Set < Object > aFewBadObjects = . . .
 * Set < String > manyBadStrings = . . .
 * / / impossible for a non - String to be in the intersection
 * SuppressWarnings ( " unchecked " )
 * Set < String > badStrings = ( Set ) Sets . intersection (
 * aFewBadObjects , manyBadStrings ) ;
 * } < / pre >
 * < p > This is unfortunate , but should come up only very rarely . */
public static < E > SetView < E > intersection ( final Set < E > set1 , final Set < ? > set2 ) { } }

implementation: checkNotNull ( set1 , "set1" ) ; checkNotNull ( set2 , "set2" ) ; return new SetView < E > ( ) { @ Override public UnmodifiableIterator < E > iterator ( ) { return new AbstractIterator < E > ( ) { final Iterator < E > itr = set1 . iterator ( ) ; @ Override protected E computeNext ( ) { while ( itr . hasNext ( ) ) { E e = itr . next ( ) ; if ( set2 . contains ( e ) ) { return e ; } } return endOfData ( ) ; } } ; } @ Override public int size ( ) { int size = 0 ; for ( E e : set1 ) { if ( set2 . contains ( e ) ) { size ++ ; } } return size ; } @ Override public boolean isEmpty ( ) { return Collections . disjoint ( set2 , set1 ) ; } @ Override public boolean contains ( Object object ) { return set1 . contains ( object ) && set2 . contains ( object ) ; } @ Override public boolean containsAll ( Collection < ? > collection ) { return set1 . containsAll ( collection ) && set2 . containsAll ( collection ) ; } } ;


signature:
public class Sets { /** * Returns an unmodifiable < b > view < / b > of the difference of two sets . The returned set contains
 * all elements that are contained by { @ code set1 } and not contained by { @ code set2 } . { @ code set2}
 * may also contain elements not present in { @ code set1 } ; these are simply ignored . The iteration
 * order of the returned set matches that of { @ code set1 } .
 * < p > Results are undefined if { @ code set1 } and { @ code set2 } are sets based on different
 * equivalence relations ( as { @ code HashSet } , { @ code TreeSet } , and the keySet of an { @ code
 * IdentityHashMap } all are ) . */
public static < E > SetView < E > difference ( final Set < E > set1 , final Set < ? > set2 ) { } }

implementation: checkNotNull ( set1 , "set1" ) ; checkNotNull ( set2 , "set2" ) ; return new SetView < E > ( ) { @ Override public UnmodifiableIterator < E > iterator ( ) { return new AbstractIterator < E > ( ) { final Iterator < E > itr = set1 . iterator ( ) ; @ Override protected E computeNext ( ) { while ( itr . hasNext ( ) ) { E e = itr . next ( ) ; if ( ! set2 . contains ( e ) ) { return e ; } } return endOfData ( ) ; } } ; } @ Override public int size ( ) { int size = 0 ; for ( E e : set1 ) { if ( ! set2 . contains ( e ) ) { size ++ ; } } return size ; } @ Override public boolean isEmpty ( ) { return set2 . containsAll ( set1 ) ; } @ Override public boolean contains ( Object element ) { return set1 . contains ( element ) && ! set2 . contains ( element ) ; } } ;


signature:
public class Sets { /** * Returns an unmodifiable < b > view < / b > of the symmetric difference of two sets . The returned set
 * contains all elements that are contained in either { @ code set1 } or { @ code set2 } but not in
 * both . The iteration order of the returned set is undefined .
 * < p > Results are undefined if { @ code set1 } and { @ code set2 } are sets based on different
 * equivalence relations ( as { @ code HashSet } , { @ code TreeSet } , and the keySet of an { @ code
 * IdentityHashMap } all are ) .
 * @ since 3.0 */
public static < E > SetView < E > symmetricDifference ( final Set < ? extends E > set1 , final Set < ? extends E > set2 ) { } }

implementation: checkNotNull ( set1 , "set1" ) ; checkNotNull ( set2 , "set2" ) ; return new SetView < E > ( ) { @ Override public UnmodifiableIterator < E > iterator ( ) { final Iterator < ? extends E > itr1 = set1 . iterator ( ) ; final Iterator < ? extends E > itr2 = set2 . iterator ( ) ; return new AbstractIterator < E > ( ) { @ Override public E computeNext ( ) { while ( itr1 . hasNext ( ) ) { E elem1 = itr1 . next ( ) ; if ( ! set2 . contains ( elem1 ) ) { return elem1 ; } } while ( itr2 . hasNext ( ) ) { E elem2 = itr2 . next ( ) ; if ( ! set1 . contains ( elem2 ) ) { return elem2 ; } } return endOfData ( ) ; } } ; } @ Override public int size ( ) { int size = 0 ; for ( E e : set1 ) { if ( ! set2 . contains ( e ) ) { size ++ ; } } for ( E e : set2 ) { if ( ! set1 . contains ( e ) ) { size ++ ; } } return size ; } @ Override public boolean isEmpty ( ) { return set1 . equals ( set2 ) ; } @ Override public boolean contains ( Object element ) { return set1 . contains ( element ) ^ set2 . contains ( element ) ; } } ;


signature:
public class Sets { /** * TODO ( kevinb ) : how to omit that last sentence when building GWT javadoc ? */
public static < E > Set < E > filter ( Set < E > unfiltered , Predicate < ? super E > predicate ) { } }

implementation:
if ( unfiltered instanceof SortedSet ) { return filter ( ( SortedSet < E > ) unfiltered , predicate ) ; } if ( unfiltered instanceof FilteredSet ) { // Support clear ( ) , removeAll ( ) , and retainAll ( ) when filtering a filtered
// collection .
FilteredSet < E > filtered = ( FilteredSet < E > ) unfiltered ; Predicate < E > combinedPredicate = Predicates . < E > and ( filtered . predicate , predicate ) ; return new FilteredSet < E > ( ( Set < E > ) filtered . unfiltered , combinedPredicate ) ; } return new FilteredSet < E > ( checkNotNull ( unfiltered ) , checkNotNull ( predicate ) ) ;


signature:
public class Sets { /** * Returns every possible list that can be formed by choosing one element from each of the given
 * sets in order ; the " n - ary < a href = " http : / / en . wikipedia . org / wiki / Cartesian _ product " > Cartesian
 * product < / a > " of the sets . For example :
 * < pre > { @ code
 * Sets . cartesianProduct ( ImmutableList . of (
 * ImmutableSet . of ( 1 , 2 ) ,
 * ImmutableSet . of ( " A " , " B " , " C " ) ) )
 * } < / pre >
 * < p > returns a set containing six lists :
 * < ul >
 * < li > { @ code ImmutableList . of ( 1 , " A " ) }
 * < li > { @ code ImmutableList . of ( 1 , " B " ) }
 * < li > { @ code ImmutableList . of ( 1 , " C " ) }
 * < li > { @ code ImmutableList . of ( 2 , " A " ) }
 * < li > { @ code ImmutableList . of ( 2 , " B " ) }
 * < li > { @ code ImmutableList . of ( 2 , " C " ) }
 * < / ul >
 * < p > The result is guaranteed to be in the " traditional " , lexicographical order for Cartesian
 * products that you would get from nesting for loops :
 * < pre > { @ code
 * for ( B b0 : sets . get ( 0 ) ) {
 * for ( B b1 : sets . get ( 1 ) ) {
 * ImmutableList < B > tuple = ImmutableList . of ( b0 , b1 , . . . ) ;
 * / / operate on tuple
 * } < / pre >
 * < p > Note that if any input set is empty , the Cartesian product will also be empty . If no sets at
 * all are provided ( an empty list ) , the resulting Cartesian product has one element , an empty
 * list ( counter - intuitive , but mathematically consistent ) .
 * < p > < i > Performance notes : < / i > while the cartesian product of sets of size { @ code m , n , p } is a
 * set of size { @ code m x n x p } , its actual memory consumption is much smaller . When the
 * cartesian set is constructed , the input sets are merely copied . Only as the resulting set is
 * iterated are the individual lists created , and these are not retained after iteration .
 * @ param sets the sets to choose elements from , in the order that the elements chosen from those
 * sets should appear in the resulting lists
 * @ param < B > any common base class shared by all axes ( often just { @ link Object } )
 * @ return the Cartesian product , as an immutable set containing immutable lists
 * @ throws NullPointerException if { @ code sets } , any one of the { @ code sets } , or any element of a
 * provided set is null
 * @ since 2.0 */
public static < B > Set < List < B > > cartesianProduct ( List < ? extends Set < ? extends B > > sets ) { } }

implementation: return CartesianSet . create ( sets ) ;


signature:
public class Sets { /** * Returns every possible list that can be formed by choosing one element from each of the given
 * sets in order ; the " n - ary < a href = " http : / / en . wikipedia . org / wiki / Cartesian _ product " > Cartesian
 * product < / a > " of the sets . For example :
 * < pre > { @ code
 * Sets . cartesianProduct (
 * ImmutableSet . of ( 1 , 2 ) ,
 * ImmutableSet . of ( " A " , " B " , " C " ) )
 * } < / pre >
 * < p > returns a set containing six lists :
 * < ul >
 * < li > { @ code ImmutableList . of ( 1 , " A " ) }
 * < li > { @ code ImmutableList . of ( 1 , " B " ) }
 * < li > { @ code ImmutableList . of ( 1 , " C " ) }
 * < li > { @ code ImmutableList . of ( 2 , " A " ) }
 * < li > { @ code ImmutableList . of ( 2 , " B " ) }
 * < li > { @ code ImmutableList . of ( 2 , " C " ) }
 * < / ul >
 * < p > The result is guaranteed to be in the " traditional " , lexicographical order for Cartesian
 * products that you would get from nesting for loops :
 * < pre > { @ code
 * for ( B b0 : sets . get ( 0 ) ) {
 * for ( B b1 : sets . get ( 1 ) ) {
 * ImmutableList < B > tuple = ImmutableList . of ( b0 , b1 , . . . ) ;
 * / / operate on tuple
 * } < / pre >
 * < p > Note that if any input set is empty , the Cartesian product will also be empty . If no sets at
 * all are provided ( an empty list ) , the resulting Cartesian product has one element , an empty
 * list ( counter - intuitive , but mathematically consistent ) .
 * < p > < i > Performance notes : < / i > while the cartesian product of sets of size { @ code m , n , p } is a
 * set of size { @ code m x n x p } , its actual memory consumption is much smaller . When the
 * cartesian set is constructed , the input sets are merely copied . Only as the resulting set is
 * iterated are the individual lists created , and these are not retained after iteration .
 * @ param sets the sets to choose elements from , in the order that the elements chosen from those
 * sets should appear in the resulting lists
 * @ param < B > any common base class shared by all axes ( often just { @ link Object } )
 * @ return the Cartesian product , as an immutable set containing immutable lists
 * @ throws NullPointerException if { @ code sets } , any one of the { @ code sets } , or any element of a
 * provided set is null
 * @ since 2.0 */
@ SafeVarargs public static < B > Set < List < B > > cartesianProduct ( Set < ? extends B > ... sets ) { } }

implementation: return cartesianProduct ( Arrays . asList ( sets ) ) ;


signature:
public class Sets { /** * Returns the set of all possible subsets of { @ code set } . For example , { @ code
 * powerSet ( ImmutableSet . of ( 1 , 2 ) ) } returns the set { @ code { { } , { 1 } , { 2 } , { 1 , 2 } } } .
 * < p > Elements appear in these subsets in the same iteration order as they appeared in the input
 * set . The order in which these subsets appear in the outer set is undefined . Note that the power
 * set of the empty set is not the empty set , but a one - element set containing the empty set .
 * < p > The returned set and its constituent sets use { @ code equals } to decide whether two elements
 * are identical , even if the input set uses a different concept of equivalence .
 * < p > < i > Performance notes : < / i > while the power set of a set with size { @ code n } is of size { @ code
 * 2 ^ n } , its memory usage is only { @ code O ( n ) } . When the power set is constructed , the input set
 * is merely copied . Only as the power set is iterated are the individual subsets created , and
 * these subsets themselves occupy only a small constant amount of memory .
 * @ param set the set of elements to construct a power set from
 * @ return the power set , as an immutable set of immutable sets
 * @ throws IllegalArgumentException if { @ code set } has more than 30 unique elements ( causing the
 * power set size to exceed the { @ code int } range )
 * @ throws NullPointerException if { @ code set } is or contains { @ code null }
 * @ see < a href = " http : / / en . wikipedia . org / wiki / Power _ set " > Power set article at Wikipedia < / a >
 * @ since 4.0 */
@ GwtCompatible ( serializable = false ) public static < E > Set < Set < E > > powerSet ( Set < E > set ) { } }

implementation: return new PowerSet < E > ( set ) ;


signature:
public class Sets { /** * Returns the set of all subsets of { @ code set } of size { @ code size } . For example , { @ code
 * combinations ( ImmutableSet . of ( 1 , 2 , 3 ) , 2 ) } returns the set { @ code { { 1 , 2 } , { 1 , 3 } , { 2 , 3 } } } .
 * < p > Elements appear in these subsets in the same iteration order as they appeared in the input
 * set . The order in which these subsets appear in the outer set is undefined .
 * < p > The returned set and its constituent sets use { @ code equals } to decide whether two elements
 * are identical , even if the input set uses a different concept of equivalence .
 * < p > < i > Performance notes : < / i > the memory usage of the returned set is only { @ code O ( n ) } . When
 * the result set is constructed , the input set is merely copied . Only as the result set is
 * iterated are the individual subsets created . Each of these subsets occupies an additional O ( n )
 * memory but only for as long as the user retains a reference to it . That is , the set returned by
 * { @ code combinations } does not retain the individual subsets .
 * @ param set the set of elements to take combinations of
 * @ param size the number of elements per combination
 * @ return the set of all combinations of { @ code size } elements from { @ code set }
 * @ throws IllegalArgumentException if { @ code size } is not between 0 and { @ code set . size ( ) }
 * inclusive
 * @ throws NullPointerException if { @ code set } is or contains { @ code null }
 * @ since 23.0 */
@ Beta public static < E > Set < Set < E > > combinations ( Set < E > set , final int size ) { } }

implementation:
final ImmutableMap < E , Integer > index = Maps . indexMap ( set ) ; checkNonnegative ( size , "size" ) ; checkArgument ( size <= index . size ( ) , "size (%s) must be <= set.size() (%s)" , size , index . size ( ) ) ; if ( size == 0 ) { return ImmutableSet . < Set < E > > of ( ImmutableSet . < E > of ( ) ) ; } else if ( size == index . size ( ) ) { return ImmutableSet . < Set < E > > of ( index . keySet ( ) ) ; } return new AbstractSet < Set < E > > ( ) { @ Override public boolean contains ( @ NullableDecl Object o ) { if ( o instanceof Set ) { Set < ? > s = ( Set < ? > ) o ; return s . size ( ) == size && index . keySet ( ) . containsAll ( s ) ; } return false ; } @ Override public Iterator < Set < E > > iterator ( ) { return new AbstractIterator < Set < E > > ( ) { final BitSet bits = new BitSet ( index . size ( ) ) ; @ Override protected Set < E > computeNext ( ) { if ( bits . isEmpty ( ) ) { bits . set ( 0 , size ) ; } else { int firstSetBit = bits . nextSetBit ( 0 ) ; int bitToFlip = bits . nextClearBit ( firstSetBit ) ; if ( bitToFlip == index . size ( ) ) { return endOfData ( ) ; } /* * The current set in sorted order looks like
 * { firstSetBit , firstSetBit + 1 , . . . , bitToFlip - 1 , . . . }
 * where it does * not * contain bitToFlip .
 * The next combination is
 * { 0 , 1 , . . . , bitToFlip - firstSetBit - 2 , bitToFlip , . . . }
 * This is lexicographically next if you look at the combinations in descending order
 * e . g . { 2 , 1 , 0 } , { 3 , 1 , 0 } , { 3 , 2 , 0 } , { 3 , 2 , 1 } , { 4 , 1 , 0 } . . . */
bits . set ( 0 , bitToFlip - firstSetBit - 1 ) ; bits . clear ( bitToFlip - firstSetBit - 1 , bitToFlip ) ; bits . set ( bitToFlip ) ; } final BitSet copy = ( BitSet ) bits . clone ( ) ; return new AbstractSet < E > ( ) { @ Override public boolean contains ( @ NullableDecl Object o ) { Integer i = index . get ( o ) ; return i != null && copy . get ( i ) ; } @ Override public Iterator < E > iterator ( ) { return new AbstractIterator < E > ( ) { int i = - 1 ; @ Override protected E computeNext ( ) { i = copy . nextSetBit ( i + 1 ) ; if ( i == - 1 ) { return endOfData ( ) ; } return index . keySet ( ) . asList ( ) . get ( i ) ; } } ; } @ Override public int size ( ) { return size ; } } ; } } ; } @ Override public int size ( ) { return IntMath . binomial ( index . size ( ) , size ) ; } @ Override public String toString ( ) { return "Sets.combinations(" + index . keySet ( ) + ", " + size + ")" ; } } ;


signature:
public class Sets { /** * An implementation for { @ link Set # hashCode ( ) } . */
static int hashCodeImpl ( Set < ? > s ) { } }

implementation:
int hashCode = 0 ; for ( Object o : s ) { hashCode += o != null ? o . hashCode ( ) : 0 ; hashCode = ~ ~ hashCode ; // Needed to deal with unusual integer overflow in GWT .
} return hashCode ;


signature:
public class Sets { /** * Returns an unmodifiable view of the specified navigable set . This method allows modules to
 * provide users with " read - only " access to internal navigable sets . Query operations on the
 * returned set " read through " to the specified set , and attempts to modify the returned set ,
 * whether direct or via its collection views , result in an { @ code UnsupportedOperationException } .
 * < p > The returned navigable set will be serializable if the specified navigable set is
 * serializable .
 * @ param set the navigable set for which an unmodifiable view is to be returned
 * @ return an unmodifiable view of the specified navigable set
 * @ since 12.0 */
public static < E > NavigableSet < E > unmodifiableNavigableSet ( NavigableSet < E > set ) { } }

implementation: if ( set instanceof ImmutableCollection || set instanceof UnmodifiableNavigableSet ) { return set ; } return new UnmodifiableNavigableSet < E > ( set ) ;


signature:
public class Sets { /** * Returns a synchronized ( thread - safe ) navigable set backed by the specified navigable set . In
 * order to guarantee serial access , it is critical that < b > all < / b > access to the backing
 * navigable set is accomplished through the returned navigable set ( or its views ) .
 * < p > It is imperative that the user manually synchronize on the returned sorted set when
 * iterating over it or any of its { @ code descendingSet } , { @ code subSet } , { @ code headSet } , or
 * { @ code tailSet } views .
 * < pre > { @ code
 * NavigableSet < E > set = synchronizedNavigableSet ( new TreeSet < E > ( ) ) ;
 * synchronized ( set ) {
 * / / Must be in the synchronized block
 * Iterator < E > it = set . iterator ( ) ;
 * while ( it . hasNext ( ) ) {
 * foo ( it . next ( ) ) ;
 * } < / pre >
 * < p > or :
 * < pre > { @ code
 * NavigableSet < E > set = synchronizedNavigableSet ( new TreeSet < E > ( ) ) ;
 * NavigableSet < E > set2 = set . descendingSet ( ) . headSet ( foo ) ;
 * synchronized ( set ) { / / Note : set , not set2 ! ! !
 * / / Must be in the synchronized block
 * Iterator < E > it = set2 . descendingIterator ( ) ;
 * while ( it . hasNext ( ) )
 * foo ( it . next ( ) ) ;
 * } < / pre >
 * < p > Failure to follow this advice may result in non - deterministic behavior .
 * < p > The returned navigable set will be serializable if the specified navigable set is
 * serializable .
 * @ param navigableSet the navigable set to be " wrapped " in a synchronized navigable set .
 * @ return a synchronized view of the specified navigable set .
 * @ since 13.0 */
@ GwtIncompatible // NavigableSet
public static < E > NavigableSet < E > synchronizedNavigableSet ( NavigableSet < E > navigableSet ) { } }

implementation: return Synchronized . navigableSet ( navigableSet ) ;


signature:
public class Sets { /** * Remove each element in an iterable from a set . */
static boolean removeAllImpl ( Set < ? > set , Iterator < ? > iterator ) { } }

implementation: boolean changed = false ; while ( iterator . hasNext ( ) ) { changed |= set . remove ( iterator . next ( ) ) ; } return changed ;


signature:
public class Sets { /** * Returns a view of the portion of { @ code set } whose elements are contained by { @ code range } .
 * < p > This method delegates to the appropriate methods of { @ link NavigableSet } ( namely { @ link
 * NavigableSet # subSet ( Object , boolean , Object , boolean ) subSet ( ) } , { @ link
 * NavigableSet # tailSet ( Object , boolean ) tailSet ( ) } , and { @ link NavigableSet # headSet ( Object ,
 * boolean ) headSet ( ) } ) to actually construct the view . Consult these methods for a full
 * description of the returned view ' s behavior .
 * < p > < b > Warning : < / b > { @ code Range } s always represent a range of values using the values ' natural
 * ordering . { @ code NavigableSet } on the other hand can specify a custom ordering via a { @ link
 * Comparator } , which can violate the natural ordering . Using this method ( or in general using
 * { @ code Range } ) with unnaturally - ordered sets can lead to unexpected and undefined behavior .
 * @ since 20.0 */
@ Beta @ GwtIncompatible // NavigableSet
public static < K extends Comparable < ? super K > > NavigableSet < K > subSet ( NavigableSet < K > set , Range < K > range ) { } }

implementation: if ( set . comparator ( ) != null && set . comparator ( ) != Ordering . natural ( ) && range . hasLowerBound ( ) && range . hasUpperBound ( ) ) { checkArgument ( set . comparator ( ) . compare ( range . lowerEndpoint ( ) , range . upperEndpoint ( ) ) <= 0 , "set is using a custom comparator which is inconsistent with the natural ordering." ) ; } if ( range . hasLowerBound ( ) && range . hasUpperBound ( ) ) { return set . subSet ( range . lowerEndpoint ( ) , range . lowerBoundType ( ) == BoundType . CLOSED , range . upperEndpoint ( ) , range . upperBoundType ( ) == BoundType . CLOSED ) ; } else if ( range . hasLowerBound ( ) ) { return set . tailSet ( range . lowerEndpoint ( ) , range . lowerBoundType ( ) == BoundType . CLOSED ) ; } else if ( range . hasUpperBound ( ) ) { return set . headSet ( range . upperEndpoint ( ) , range . upperBoundType ( ) == BoundType . CLOSED ) ; } return checkNotNull ( set ) ;


signature:
public class CharEscaper { /** * Returns the escaped form of a given literal string .
 * @ param string the literal string to be escaped
 * @ return the escaped form of { @ code string }
 * @ throws NullPointerException if { @ code string } is null */
@ Override public String escape ( String string ) { } }

implementation:
checkNotNull ( string ) ; // GWT specific check ( do not optimize )
// Inlineable fast - path loop which hands off to escapeSlow ( ) only if needed
int length = string . length ( ) ; for ( int index = 0 ; index < length ; index ++ ) { if ( escape ( string . charAt ( index ) ) != null ) { return escapeSlow ( string , index ) ; } } return string ;


signature:
public class CharEscaper { /** * Helper method to grow the character buffer as needed , this only happens once in a while so it ' s
 * ok if it ' s in a method call . If the index passed in is 0 then no copying will be done . */
private static char [ ] growBuffer ( char [ ] dest , int index , int size ) { } }

implementation:
if ( size < 0 ) { // overflow - should be OutOfMemoryError but GWT / j2cl don ' t support it
throw new AssertionError ( "Cannot increase internal buffer any further" ) ; } char [ ] copy = new char [ size ] ; if ( index > 0 ) { System . arraycopy ( dest , 0 , copy , 0 , index ) ; } return copy ;


signature:
public class Streams { /** * Returns a sequential { @ link Stream } of the contents of { @ code iterable } , delegating to { @ link
 * Collection # stream } if possible . */
public static < T > Stream < T > stream ( Iterable < T > iterable ) { } }

implementation: return ( iterable instanceof Collection ) ? ( ( Collection < T > ) iterable ) . stream ( ) : StreamSupport . stream ( iterable . spliterator ( ) , false ) ;


signature:
public class Streams { /** * Returns { @ link Collection # stream } .
 * @ deprecated There is no reason to use this ; just invoke { @ code collection . stream ( ) } directly . */
@ Beta @ Deprecated public static < T > Stream < T > stream ( Collection < T > collection ) { } }

implementation: return collection . stream ( ) ;


signature:
public class Streams { /** * If a value is present in { @ code optional } , returns a stream containing only that element ,
 * otherwise returns an empty stream . */
@ Beta public static < T > Stream < T > stream ( com . google . common . base . Optional < T > optional ) { } }

implementation: return optional . isPresent ( ) ? Stream . of ( optional . get ( ) ) : Stream . of ( ) ;


signature:
public class Streams { /** * If a value is present in { @ code optional } , returns a stream containing only that element ,
 * otherwise returns an empty stream .
 * < p > < b > Java 9 users : < / b > use { @ code optional . stream ( ) } instead . */
@ Beta public static < T > Stream < T > stream ( java . util . Optional < T > optional ) { } }


signature:
public class Streams { /** * If a value is present in { @ code optional } , returns a stream containing only that element ,
 * otherwise returns an empty stream .
 * < p > < b > Java 9 users : < / b > use { @ code optional . stream ( ) } instead . */
@ Beta public static IntStream stream ( OptionalInt optional ) { } }

implementation: return optional . isPresent ( ) ? IntStream . of ( optional . getAsInt ( ) ) : IntStream . empty ( ) ;


signature:
public class Streams { /** * If a value is present in { @ code optional } , returns a stream containing only that element ,
 * otherwise returns an empty stream .
 * < p > < b > Java 9 users : < / b > use { @ code optional . stream ( ) } instead . */
@ Beta public static LongStream stream ( OptionalLong optional ) { } }

implementation: return optional . isPresent ( ) ? LongStream . of ( optional . getAsLong ( ) ) : LongStream . empty ( ) ;


signature:
public class Streams { /** * If a value is present in { @ code optional } , returns a stream containing only that element ,
 * otherwise returns an empty stream .
 * < p > < b > Java 9 users : < / b > use { @ code optional . stream ( ) } instead . */
@ Beta public static DoubleStream stream ( OptionalDouble optional ) { } }

implementation: return optional . isPresent ( ) ? DoubleStream . of ( optional . getAsDouble ( ) ) : DoubleStream . empty ( ) ;


signature:
public class Streams { /** * Returns a { @ link Stream } containing the elements of the first stream , followed by the elements
 * of the second stream , and so on .
 * < p > This is equivalent to { @ code Stream . of ( streams ) . flatMap ( stream - > stream ) } , but the returned
 * stream may perform better .
 * @ see Stream # concat ( Stream , Stream ) */
@ SafeVarargs public static < T > Stream < T > concat ( Stream < ? extends T > ... streams ) { } }

implementation:
// TODO ( lowasser ) : consider an implementation that can support SUBSIZED
boolean isParallel = false ; int characteristics = Spliterator . ORDERED | Spliterator . SIZED | Spliterator . NONNULL ; long estimatedSize = 0L ; ImmutableList . Builder < Spliterator < ? extends T > > splitrsBuilder = new ImmutableList . Builder < > ( streams . length ) ; for ( Stream < ? extends T > stream : streams ) { isParallel |= stream . isParallel ( ) ; Spliterator < ? extends T > splitr = stream . spliterator ( ) ; splitrsBuilder . add ( splitr ) ; characteristics &= splitr . characteristics ( ) ; estimatedSize = LongMath . saturatedAdd ( estimatedSize , splitr . estimateSize ( ) ) ; } return StreamSupport . stream ( CollectSpliterators . flatMap ( splitrsBuilder . build ( ) . spliterator ( ) , splitr -> ( Spliterator < T > ) splitr , characteristics , estimatedSize ) , isParallel ) . onClose ( ( ) -> { for ( Stream < ? extends T > stream : streams ) { stream . close ( ) ; } } ) ;


signature:
public class Streams { /** * Returns an { @ link IntStream } containing the elements of the first stream , followed by the
 * elements of the second stream , and so on .
 * < p > This is equivalent to { @ code Stream . of ( streams ) . flatMapToInt ( stream - > stream ) } , but the
 * returned stream may perform better .
 * @ see IntStream # concat ( IntStream , IntStream ) */
public static IntStream concat ( IntStream ... streams ) { } }

implementation:
// TODO ( lowasser ) : optimize this later
return Stream . of ( streams ) . flatMapToInt ( stream -> stream ) ;


signature:
public class Streams { /** * Returns a { @ link LongStream } containing the elements of the first stream , followed by the
 * elements of the second stream , and so on .
 * < p > This is equivalent to { @ code Stream . of ( streams ) . flatMapToLong ( stream - > stream ) } , but the
 * returned stream may perform better .
 * @ see LongStream # concat ( LongStream , LongStream ) */
public static LongStream concat ( LongStream ... streams ) { } }

implementation:
// TODO ( lowasser ) : optimize this later
return Stream . of ( streams ) . flatMapToLong ( stream -> stream ) ;


signature:
public class Streams { /** * Returns a { @ link DoubleStream } containing the elements of the first stream , followed by the
 * elements of the second stream , and so on .
 * < p > This is equivalent to { @ code Stream . of ( streams ) . flatMapToDouble ( stream - > stream ) } , but the
 * returned stream may perform better .
 * @ see DoubleStream # concat ( DoubleStream , DoubleStream ) */
public static DoubleStream concat ( DoubleStream ... streams ) { } }

implementation:
// TODO ( lowasser ) : optimize this later
return Stream . of ( streams ) . flatMapToDouble ( stream -> stream ) ;


signature:
public class Streams { /** * Returns a stream in which each element is the result of passing the corresponding elementY of
 * each of { @ code streamA } and { @ code streamB } to { @ code function } .
 * < p > For example :
 * < pre > { @ code
 * Streams . zip (
 * Stream . of ( " foo1 " , " foo2 " , " foo3 " ) ,
 * Stream . of ( " bar1 " , " bar2 " ) ,
 * ( arg1 , arg2 ) - > arg1 + " : " + arg2)
 * } < / pre >
 * < p > will return { @ code Stream . of ( " foo1 : bar1 " , " foo2 : bar2 " ) } .
 * < p > The resulting stream will only be as long as the shorter of the two input streams ; if one
 * stream is longer , its extra elements will be ignored .
 * < p > Note that if you are calling { @ link Stream # forEach } on the resulting stream , you might want
 * to consider using { @ link # forEachPair } instead of this method .
 * < p > < b > Performance note : < / b > The resulting stream is not < a
 * href = " http : / / gee . cs . oswego . edu / dl / html / StreamParallelGuidance . html " > efficiently splittable < / a > .
 * This may harm parallel performance . */
@ Beta public static < A , B , R > Stream < R > zip ( Stream < A > streamA , Stream < B > streamB , BiFunction < ? super A , ? super B , R > function ) { } }

implementation:
checkNotNull ( streamA ) ; checkNotNull ( streamB ) ; checkNotNull ( function ) ; boolean isParallel = streamA . isParallel ( ) || streamB . isParallel ( ) ; // same as Stream . concat
Spliterator < A > splitrA = streamA . spliterator ( ) ; Spliterator < B > splitrB = streamB . spliterator ( ) ; int characteristics = splitrA . characteristics ( ) & splitrB . characteristics ( ) & ( Spliterator . SIZED | Spliterator . ORDERED ) ; Iterator < A > itrA = Spliterators . iterator ( splitrA ) ; Iterator < B > itrB = Spliterators . iterator ( splitrB ) ; return StreamSupport . stream ( new AbstractSpliterator < R > ( Math . min ( splitrA . estimateSize ( ) , splitrB . estimateSize ( ) ) , characteristics ) { @ Override public boolean tryAdvance ( Consumer < ? super R > action ) { if ( itrA . hasNext ( ) && itrB . hasNext ( ) ) { action . accept ( function . apply ( itrA . next ( ) , itrB . next ( ) ) ) ; return true ; } return false ; } } , isParallel ) . onClose ( streamA :: close ) . onClose ( streamB :: close ) ;


signature:
public class Streams { /** * Invokes { @ code consumer } once for each pair of < i > corresponding < / i > elements in { @ code streamA }
 * and { @ code streamB } . If one stream is longer than the other , the extra elements are silently
 * ignored . Elements passed to the consumer are guaranteed to come from the same position in their
 * respective source streams . For example :
 * < pre > { @ code
 * Streams . forEachPair (
 * Stream . of ( " foo1 " , " foo2 " , " foo3 " ) ,
 * Stream . of ( " bar1 " , " bar2 " ) ,
 * ( arg1 , arg2 ) - > System . out . println ( arg1 + " : " + arg2)
 * } < / pre >
 * < p > will print :
 * < pre > { @ code
 * foo1 : bar1
 * foo2 : bar2
 * } < / pre >
 * < p > < b > Warning : < / b > If either supplied stream is a parallel stream , the same correspondence
 * between elements will be made , but the order in which those pairs of elements are passed to the
 * consumer is < i > not < / i > defined .
 * < p > Note that many usages of this method can be replaced with simpler calls to { @ link # zip } .
 * This method behaves equivalently to { @ linkplain # zip zipping } the stream elements into
 * temporary pair objects and then using { @ link Stream # forEach } on that stream .
 * @ since 22.0 */
@ Beta public static < A , B > void forEachPair ( Stream < A > streamA , Stream < B > streamB , BiConsumer < ? super A , ? super B > consumer ) { } }

implementation: checkNotNull ( consumer ) ; if ( streamA . isParallel ( ) || streamB . isParallel ( ) ) { zip ( streamA , streamB , TemporaryPair :: new ) . forEach ( pair -> consumer . accept ( pair . a , pair . b ) ) ; } else { Iterator < A > iterA = streamA . iterator ( ) ; Iterator < B > iterB = streamB . iterator ( ) ; while ( iterA . hasNext ( ) && iterB . hasNext ( ) ) { consumer . accept ( iterA . next ( ) , iterB . next ( ) ) ; } }


signature:
public class Streams { /** * Returns a stream consisting of the results of applying the given function to the elements of
 * { @ code stream } and their indices in the stream . For example ,
 * < pre > { @ code
 * mapWithIndex (
 * Stream . of ( " a " , " b " , " c " ) ,
 * ( str , index ) - > str + " : " + index )
 * } < / pre >
 * < p > would return { @ code Stream . of ( " a : 0 " , " b : 1 " , " c : 2 " ) } .
 * < p > The resulting stream is < a
 * href = " http : / / gee . cs . oswego . edu / dl / html / StreamParallelGuidance . html " > efficiently splittable < / a >
 * if and only if { @ code stream } was efficiently splittable and its underlying spliterator
 * reported { @ link Spliterator # SUBSIZED } . This is generally the case if the underlying stream
 * comes from a data structure supporting efficient indexed random access , typically an array or
 * list .
 * < p > The order of the resulting stream is defined if and only if the order of the original stream
 * was defined . */
@ Beta public static < T , R > Stream < R > mapWithIndex ( Stream < T > stream , FunctionWithIndex < ? super T , ? extends R > function ) { } }

implementation: checkNotNull ( stream ) ; checkNotNull ( function ) ; boolean isParallel = stream . isParallel ( ) ; Spliterator < T > fromSpliterator = stream . spliterator ( ) ; if ( ! fromSpliterator . hasCharacteristics ( Spliterator . SUBSIZED ) ) { Iterator < T > fromIterator = Spliterators . iterator ( fromSpliterator ) ; return StreamSupport . stream ( new AbstractSpliterator < R > ( fromSpliterator . estimateSize ( ) , fromSpliterator . characteristics ( ) & ( Spliterator . ORDERED | Spliterator . SIZED ) ) { long index = 0 ; @ Override public boolean tryAdvance ( Consumer < ? super R > action ) { if ( fromIterator . hasNext ( ) ) { action . accept ( function . apply ( fromIterator . next ( ) , index ++ ) ) ; return true ; } return false ; } } , isParallel ) . onClose ( stream :: close ) ; } class Splitr extends MapWithIndexSpliterator < Spliterator < T > , R , Splitr > implements Consumer < T > { @ Nullable T holder ; Splitr ( Spliterator < T > splitr , long index ) { super ( splitr , index ) ; } @ Override public void accept ( @ Nullable T t ) { this . holder = t ; } @ Override public boolean tryAdvance ( Consumer < ? super R > action ) { if ( fromSpliterator . tryAdvance ( this ) ) { try { action . accept ( function . apply ( holder , index ++ ) ) ; return true ; } finally { holder = null ; } } return false ; } @ Override Splitr createSplit ( Spliterator < T > from , long i ) { return new Splitr ( from , i ) ; } } return StreamSupport . stream ( new Splitr ( fromSpliterator , 0 ) , isParallel ) . onClose ( stream :: close ) ;


signature:
public class Streams { /** * Returns a stream consisting of the results of applying the given function to the elements of
 * { @ code stream } and their indexes in the stream . For example ,
 * < pre > { @ code
 * mapWithIndex (
 * IntStream . of ( 0 , 1 , 2 ) ,
 * ( i , index ) - > i + " : " + index )
 * } < / pre >
 * < p > . . . would return { @ code Stream . of ( " 0:0 " , " 1:1 " , " 2:2 " ) } .
 * < p > The resulting stream is < a
 * href = " http : / / gee . cs . oswego . edu / dl / html / StreamParallelGuidance . html " > efficiently splittable < / a >
 * if and only if { @ code stream } was efficiently splittable and its underlying spliterator
 * reported { @ link Spliterator # SUBSIZED } . This is generally the case if the underlying stream
 * comes from a data structure supporting efficient indexed random access , typically an array or
 * list .
 * < p > The order of the resulting stream is defined if and only if the order of the original stream
 * was defined . */
@ Beta public static < R > Stream < R > mapWithIndex ( IntStream stream , IntFunctionWithIndex < R > function ) { } }

implementation: checkNotNull ( stream ) ; checkNotNull ( function ) ; boolean isParallel = stream . isParallel ( ) ; Spliterator . OfInt fromSpliterator = stream . spliterator ( ) ; if ( ! fromSpliterator . hasCharacteristics ( Spliterator . SUBSIZED ) ) { PrimitiveIterator . OfInt fromIterator = Spliterators . iterator ( fromSpliterator ) ; return StreamSupport . stream ( new AbstractSpliterator < R > ( fromSpliterator . estimateSize ( ) , fromSpliterator . characteristics ( ) & ( Spliterator . ORDERED | Spliterator . SIZED ) ) { long index = 0 ; @ Override public boolean tryAdvance ( Consumer < ? super R > action ) { if ( fromIterator . hasNext ( ) ) { action . accept ( function . apply ( fromIterator . nextInt ( ) , index ++ ) ) ; return true ; } return false ; } } , isParallel ) . onClose ( stream :: close ) ; } class Splitr extends MapWithIndexSpliterator < Spliterator . OfInt , R , Splitr > implements IntConsumer , Spliterator < R > { int holder ; Splitr ( Spliterator . OfInt splitr , long index ) { super ( splitr , index ) ; } @ Override public void accept ( int t ) { this . holder = t ; } @ Override public boolean tryAdvance ( Consumer < ? super R > action ) { if ( fromSpliterator . tryAdvance ( this ) ) { action . accept ( function . apply ( holder , index ++ ) ) ; return true ; } return false ; } @ Override Splitr createSplit ( Spliterator . OfInt from , long i ) { return new Splitr ( from , i ) ; } } return StreamSupport . stream ( new Splitr ( fromSpliterator , 0 ) , isParallel ) . onClose ( stream :: close ) ;


signature:
public class Streams { /** * Returns the last element of the specified stream , or { @ link java . util . Optional # empty } if the
 * stream is empty .
 * < p > Equivalent to { @ code stream . reduce ( ( a , b ) - > b ) } , but may perform significantly better . This
 * method ' s runtime will be between O ( log n ) and O ( n ) , performing better on < a
 * href = " http : / / gee . cs . oswego . edu / dl / html / StreamParallelGuidance . html " > efficiently splittable < / a >
 * streams .
 * < p > If the stream has nondeterministic order , this has equivalent semantics to { @ link
 * Stream # findAny } ( which you might as well use ) .
 * @ see Stream # findFirst ( )
 * @ throws NullPointerException if the last element of the stream is null */
@ Beta public static < T > java . util . Optional < T > findLast ( Stream < T > stream ) { } }

implementation:
class OptionalState { boolean set = false ; T value = null ; void set ( @ Nullable T value ) { this . set = true ; this . value = value ; } T get ( ) { checkState ( set ) ; return value ; } } OptionalState state = new OptionalState ( ) ; Deque < Spliterator < T > > splits = new ArrayDeque < > ( ) ; splits . addLast ( stream . spliterator ( ) ) ; while ( ! splits . isEmpty ( ) ) { Spliterator < T > spliterator = splits . removeLast ( ) ; if ( spliterator . getExactSizeIfKnown ( ) == 0 ) { continue ; // drop this split
} // Many spliterators will have trySplits that are SUBSIZED even if they are not themselves
// SUBSIZED .
if ( spliterator . hasCharacteristics ( Spliterator . SUBSIZED ) ) { // we can drill down to exactly the smallest nonempty spliterator
while ( true ) { Spliterator < T > prefix = spliterator . trySplit ( ) ; if ( prefix == null || prefix . getExactSizeIfKnown ( ) == 0 ) { break ; } else if ( spliterator . getExactSizeIfKnown ( ) == 0 ) { spliterator = prefix ; break ; } } // spliterator is known to be nonempty now
spliterator . forEachRemaining ( state :: set ) ; return java . util . Optional . of ( state . get ( ) ) ; } Spliterator < T > prefix = spliterator . trySplit ( ) ; if ( prefix == null || prefix . getExactSizeIfKnown ( ) == 0 ) { // we can ' t split this any further
spliterator . forEachRemaining ( state :: set ) ; if ( state . set ) { return java . util . Optional . of ( state . get ( ) ) ; } // fall back to the last split
continue ; } splits . addLast ( prefix ) ; splits . addLast ( spliterator ) ; } return java . util . Optional . empty ( ) ;


signature:
public class Streams { /** * Returns the last element of the specified stream , or { @ link OptionalInt # empty } if the stream is
 * empty .
 * < p > Equivalent to { @ code stream . reduce ( ( a , b ) - > b ) } , but may perform significantly better . This
 * method ' s runtime will be between O ( log n ) and O ( n ) , performing better on < a
 * href = " http : / / gee . cs . oswego . edu / dl / html / StreamParallelGuidance . html " > efficiently splittable < / a >
 * streams .
 * @ see IntStream # findFirst ( )
 * @ throws NullPointerException if the last element of the stream is null */
@ Beta public static OptionalInt findLast ( IntStream stream ) { } }

implementation:
// findLast ( Stream ) does some allocation , so we might as well box some more
java . util . Optional < Integer > boxedLast = findLast ( stream . boxed ( ) ) ; return boxedLast . isPresent ( ) ? OptionalInt . of ( boxedLast . get ( ) ) : OptionalInt . empty ( ) ;


signature:
public class Streams { /** * Returns the last element of the specified stream , or { @ link OptionalLong # empty } if the stream
 * is empty .
 * < p > Equivalent to { @ code stream . reduce ( ( a , b ) - > b ) } , but may perform significantly better . This
 * method ' s runtime will be between O ( log n ) and O ( n ) , performing better on < a
 * href = " http : / / gee . cs . oswego . edu / dl / html / StreamParallelGuidance . html " > efficiently splittable < / a >
 * streams .
 * @ see LongStream # findFirst ( )
 * @ throws NullPointerException if the last element of the stream is null */
@ Beta public static OptionalLong findLast ( LongStream stream ) { } }

implementation:
// findLast ( Stream ) does some allocation , so we might as well box some more
java . util . Optional < Long > boxedLast = findLast ( stream . boxed ( ) ) ; return boxedLast . isPresent ( ) ? OptionalLong . of ( boxedLast . get ( ) ) : OptionalLong . empty ( ) ;


signature:
public class Streams { /** * Returns the last element of the specified stream , or { @ link OptionalDouble # empty } if the stream
 * is empty .
 * < p > Equivalent to { @ code stream . reduce ( ( a , b ) - > b ) } , but may perform significantly better . This
 * method ' s runtime will be between O ( log n ) and O ( n ) , performing better on < a
 * href = " http : / / gee . cs . oswego . edu / dl / html / StreamParallelGuidance . html " > efficiently splittable < / a >
 * streams .
 * @ see DoubleStream # findFirst ( )
 * @ throws NullPointerException if the last element of the stream is null */
@ Beta public static OptionalDouble findLast ( DoubleStream stream ) { } }

implementation:
// findLast ( Stream ) does some allocation , so we might as well box some more
java . util . Optional < Double > boxedLast = findLast ( stream . boxed ( ) ) ; return boxedLast . isPresent ( ) ? OptionalDouble . of ( boxedLast . get ( ) ) : OptionalDouble . empty ( ) ;


signature:
public class Lists { /** * Creates a < i > mutable < / i > { @ code ArrayList } instance containing the given elements .
 * < p > < b > Note : < / b > essentially the only reason to use this method is when you will need to add or
 * remove elements later . Otherwise , for non - null elements use { @ link ImmutableList # of ( ) } ( for
 * varargs ) or { @ link ImmutableList # copyOf ( Object [ ] ) } ( for an array ) instead . If any elements
 * might be null , or you need support for { @ link List # set ( int , Object ) } , use { @ link
 * Arrays # asList } .
 * < p > Note that even when you do need the ability to add or remove , this method provides only a
 * tiny bit of syntactic sugar for { @ code newArrayList ( } { @ link Arrays # asList asList } { @ code
 * ( . . . ) ) } , or for creating an empty list then calling { @ link Collections # addAll } . This method is
 * not actually very useful and will likely be deprecated in the future . */
@ SafeVarargs @ GwtCompatible ( serializable = true ) public static < E > ArrayList < E > newArrayList ( E ... elements ) { } }

implementation:
checkNotNull ( elements ) ; // for GWT
// Avoid integer overflow when a large array is passed in
int capacity = computeArrayListCapacity ( elements . length ) ; ArrayList < E > list = new ArrayList < > ( capacity ) ; Collections . addAll ( list , elements ) ; return list ;


signature:
public class Lists { /** * Creates a < i > mutable < / i > { @ code ArrayList } instance containing the given elements ; a very thin
 * shortcut for creating an empty list then calling { @ link Iterables # addAll } .
 * < p > < b > Note : < / b > if mutability is not required and the elements are non - null , use { @ link
 * ImmutableList # copyOf ( Iterable ) } instead . ( Or , change { @ code elements } to be a { @ link
 * FluentIterable } and call { @ code elements . toList ( ) } . )
 * < p > < b > Note for Java 7 and later : < / b > if { @ code elements } is a { @ link Collection } , you don ' t
 * need this method . Use the { @ code ArrayList } { @ linkplain ArrayList # ArrayList ( Collection )
 * constructor } directly , taking advantage of the new < a href = " http : / / goo . gl / iz2Wi " > " diamond "
 * syntax < / a > . */
@ GwtCompatible ( serializable = true ) public static < E > ArrayList < E > newArrayList ( Iterable < ? extends E > elements ) { } }

implementation:
checkNotNull ( elements ) ; // for GWT
// Let ArrayList ' s sizing logic work , if possible
return ( elements instanceof Collection ) ? new ArrayList < > ( Collections2 . cast ( elements ) ) : newArrayList ( elements . iterator ( ) ) ;


signature:
public class Lists { /** * Creates a < i > mutable < / i > { @ code ArrayList } instance containing the given elements ; a very thin
 * shortcut for creating an empty list and then calling { @ link Iterators # addAll } .
 * < p > < b > Note : < / b > if mutability is not required and the elements are non - null , use { @ link
 * ImmutableList # copyOf ( Iterator ) } instead . */
@ GwtCompatible ( serializable = true ) public static < E > ArrayList < E > newArrayList ( Iterator < ? extends E > elements ) { } }

implementation: ArrayList < E > list = newArrayList ( ) ; Iterators . addAll ( list , elements ) ; return list ;


signature:
public class Lists { /** * Creates an { @ code ArrayList } instance backed by an array with the specified initial size ;
 * simply delegates to { @ link ArrayList # ArrayList ( int ) } .
 * < p > < b > Note for Java 7 and later : < / b > this method is now unnecessary and should be treated as
 * deprecated . Instead , use { @ code new } { @ link ArrayList # ArrayList ( int ) ArrayList } { @ code < > ( int ) }
 * directly , taking advantage of the new < a href = " http : / / goo . gl / iz2Wi " > " diamond " syntax < / a > .
 * ( Unlike here , there is no risk of overload ambiguity , since the { @ code ArrayList } constructors
 * very wisely did not accept varargs . )
 * @ param initialArraySize the exact size of the initial backing array for the returned array list
 * ( { @ code ArrayList } documentation calls this value the " capacity " )
 * @ return a new , empty { @ code ArrayList } which is guaranteed not to resize itself unless its size
 * reaches { @ code initialArraySize + 1}
 * @ throws IllegalArgumentException if { @ code initialArraySize } is negative */
@ GwtCompatible ( serializable = true ) public static < E > ArrayList < E > newArrayListWithCapacity ( int initialArraySize ) { } }

implementation:
checkNonnegative ( initialArraySize , "initialArraySize" ) ; // for GWT .
return new ArrayList < > ( initialArraySize ) ;


signature:
public class Lists { /** * Creates a < i > mutable < / i > { @ code LinkedList } instance containing the given elements ; a very thin
 * shortcut for creating an empty list then calling { @ link Iterables # addAll } .
 * < p > < b > Note : < / b > if mutability is not required and the elements are non - null , use { @ link
 * ImmutableList # copyOf ( Iterable ) } instead . ( Or , change { @ code elements } to be a { @ link
 * FluentIterable } and call { @ code elements . toList ( ) } . )
 * < p > < b > Performance note : < / b > { @ link ArrayList } and { @ link java . util . ArrayDeque } consistently
 * outperform { @ code LinkedList } except in certain rare and specific situations . Unless you have
 * spent a lot of time benchmarking your specific needs , use one of those instead .
 * < p > < b > Note for Java 7 and later : < / b > if { @ code elements } is a { @ link Collection } , you don ' t
 * need this method . Use the { @ code LinkedList } { @ linkplain LinkedList # LinkedList ( Collection )
 * constructor } directly , taking advantage of the new < a href = " http : / / goo . gl / iz2Wi " > " diamond "
 * syntax < / a > . */
@ GwtCompatible ( serializable = true ) public static < E > LinkedList < E > newLinkedList ( Iterable < ? extends E > elements ) { } }

implementation: LinkedList < E > list = newLinkedList ( ) ; Iterables . addAll ( list , elements ) ; return list ;


signature:
public class Lists { /** * Creates a { @ code CopyOnWriteArrayList } instance containing the given elements .
 * @ param elements the elements that the list should contain , in order
 * @ return a new { @ code CopyOnWriteArrayList } containing those elements
 * @ since 12.0 */
@ GwtIncompatible // CopyOnWriteArrayList
public static < E > CopyOnWriteArrayList < E > newCopyOnWriteArrayList ( Iterable < ? extends E > elements ) { } }

implementation:
// We copy elements to an ArrayList first , rather than incurring the
// quadratic cost of adding them to the COWAL directly .
Collection < ? extends E > elementsCollection = ( elements instanceof Collection ) ? Collections2 . cast ( elements ) : newArrayList ( elements ) ; return new CopyOnWriteArrayList < > ( elementsCollection ) ;


signature:
public class Lists { /** * Returns an unmodifiable list containing the specified first element and backed by the specified
 * array of additional elements . Changes to the { @ code rest } array will be reflected in the
 * returned list . Unlike { @ link Arrays # asList } , the returned list is unmodifiable .
 * < p > This is useful when a varargs method needs to use a signature such as { @ code ( Foo firstFoo ,
 * Foo . . . moreFoos ) } , in order to avoid overload ambiguity or to enforce a minimum argument count .
 * < p > The returned list is serializable and implements { @ link RandomAccess } .
 * @ param first the first element
 * @ param rest an array of additional elements , possibly empty
 * @ return an unmodifiable list containing the specified elements */
public static < E > List < E > asList ( @ NullableDecl E first , E [ ] rest ) { } }

implementation: return new OnePlusArrayList < > ( first , rest ) ;


signature:
public class Lists { /** * Returns an unmodifiable list containing the specified first and second element , and backed by
 * the specified array of additional elements . Changes to the { @ code rest } array will be reflected
 * in the returned list . Unlike { @ link Arrays # asList } , the returned list is unmodifiable .
 * < p > This is useful when a varargs method needs to use a signature such as { @ code ( Foo firstFoo ,
 * Foo secondFoo , Foo . . . moreFoos ) } , in order to avoid overload ambiguity or to enforce a minimum
 * argument count .
 * < p > The returned list is serializable and implements { @ link RandomAccess } .
 * @ param first the first element
 * @ param second the second element
 * @ param rest an array of additional elements , possibly empty
 * @ return an unmodifiable list containing the specified elements */
public static < E > List < E > asList ( @ NullableDecl E first , @ NullableDecl E second , E [ ] rest ) { } }

implementation: return new TwoPlusArrayList < > ( first , second , rest ) ;


signature:
public class Lists { /** * Returns consecutive { @ linkplain List # subList ( int , int ) sublists } of a list , each of the same
 * size ( the final list may be smaller ) . For example , partitioning a list containing { @ code [ a , b ,
 * c , d , e ] } with a partition size of 3 yields { @ code [ [ a , b , c ] , [ d , e ] ] } - - an outer list
 * containing two inner lists of three and two elements , all in the original order .
 * < p > The outer list is unmodifiable , but reflects the latest state of the source list . The inner
 * lists are sublist views of the original list , produced on demand using { @ link List # subList ( int ,
 * int ) } , and are subject to all the usual caveats about modification as explained in that API .
 * @ param list the list to return consecutive sublists of
 * @ param size the desired size of each sublist ( the last may be smaller )
 * @ return a list of consecutive sublists
 * @ throws IllegalArgumentException if { @ code partitionSize } is nonpositive */
public static < T > List < List < T > > partition ( List < T > list , int size ) { } }

implementation: checkNotNull ( list ) ; checkArgument ( size > 0 ) ; return ( list instanceof RandomAccess ) ? new RandomAccessPartition < > ( list , size ) : new Partition < > ( list , size ) ;


signature:
public class Lists { /** * An implementation of { @ link List # hashCode ( ) } . */
static int hashCodeImpl ( List < ? > list ) { } }

implementation:
// TODO ( lowasser ) : worth optimizing for RandomAccess ?
int hashCode = 1 ; for ( Object o : list ) { hashCode = 31 * hashCode + ( o == null ? 0 : o . hashCode ( ) ) ; hashCode = ~ ~ hashCode ; // needed to deal with GWT integer overflow
} return hashCode ;


signature:
public class Lists { /** * An implementation of { @ link List # addAll ( int , Collection ) } . */
static < E > boolean addAllImpl ( List < E > list , int index , Iterable < ? extends E > elements ) { } }

implementation: boolean changed = false ; ListIterator < E > listIterator = list . listIterator ( index ) ; for ( E e : elements ) { listIterator . add ( e ) ; changed = true ; } return changed ;


signature:
public class Lists { /** * An implementation of { @ link List # lastIndexOf ( Object ) } . */
static int lastIndexOfImpl ( List < ? > list , @ NullableDecl Object element ) { } }

implementation: if ( list instanceof RandomAccess ) { return lastIndexOfRandomAccess ( list , element ) ; } else { ListIterator < ? > listIterator = list . listIterator ( list . size ( ) ) ; while ( listIterator . hasPrevious ( ) ) { if ( Objects . equal ( element , listIterator . previous ( ) ) ) { return listIterator . nextIndex ( ) ; } } return - 1 ; }


signature:
public class Lists { /** * An implementation of { @ link List # subList ( int , int ) } . */
static < E > List < E > subListImpl ( final List < E > list , int fromIndex , int toIndex ) { } }

implementation: List < E > wrapper ; if ( list instanceof RandomAccess ) { wrapper = new RandomAccessListWrapper < E > ( list ) { @ Override public ListIterator < E > listIterator ( int index ) { return backingList . listIterator ( index ) ; } private static final long serialVersionUID = 0 ; } ; } else { wrapper = new AbstractListWrapper < E > ( list ) { @ Override public ListIterator < E > listIterator ( int index ) { return backingList . listIterator ( index ) ; } private static final long serialVersionUID = 0 ; } ; } return wrapper . subList ( fromIndex , toIndex ) ;


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

implementation: return ( List < T > ) iterable ;


signature:
public class FuturesGetChecked { /** * Implementation of { @ link Futures # getChecked ( Future , Class ) } . */
@ CanIgnoreReturnValue @ VisibleForTesting static < V , X extends Exception > V getChecked ( GetCheckedTypeValidator validator , Future < V > future , Class < X > exceptionClass ) throws X { } }

implementation: validator . validateClass ( exceptionClass ) ; try { return future . get ( ) ; } catch ( InterruptedException e ) { currentThread ( ) . interrupt ( ) ; throw newWithCause ( exceptionClass , e ) ; } catch ( ExecutionException e ) { wrapAndThrowExceptionOrError ( e . getCause ( ) , exceptionClass ) ; throw new AssertionError ( ) ; }


signature:
public class FuturesGetChecked { /** * Implementation of { @ link Futures # getChecked ( Future , Class , long , TimeUnit ) } . */
@ CanIgnoreReturnValue static < V , X extends Exception > V getChecked ( Future < V > future , Class < X > exceptionClass , long timeout , TimeUnit unit ) throws X { } }

implementation:
// TODO ( cpovirk ) : benchmark a version of this method that accepts a GetCheckedTypeValidator
bestGetCheckedTypeValidator ( ) . validateClass ( exceptionClass ) ; try { return future . get ( timeout , unit ) ; } catch ( InterruptedException e ) { currentThread ( ) . interrupt ( ) ; throw newWithCause ( exceptionClass , e ) ; } catch ( TimeoutException e ) { throw newWithCause ( exceptionClass , e ) ; } catch ( ExecutionException e ) { wrapAndThrowExceptionOrError ( e . getCause ( ) , exceptionClass ) ; throw new AssertionError ( ) ; }


signature:
public class FuturesGetChecked { /** * TODO ( cpovirk ) : change parameter order to match other helper methods ( Class , Throwable ) ? */
private static < X extends Exception > void wrapAndThrowExceptionOrError ( Throwable cause , Class < X > exceptionClass ) throws X { } }

implementation: if ( cause instanceof Error ) { throw new ExecutionError ( ( Error ) cause ) ; } if ( cause instanceof RuntimeException ) { throw new UncheckedExecutionException ( cause ) ; } throw newWithCause ( exceptionClass , cause ) ;


signature:
public class FuturesGetChecked { /** * TODO ( user ) : FutureChecker interface for these to be static methods on ? If so , refer to it in
 * the ( static - method ) Futures . getChecked documentation */
private static boolean hasConstructorUsableByGetChecked ( Class < ? extends Exception > exceptionClass ) { } }

implementation: try { Exception unused = newWithCause ( exceptionClass , new Exception ( ) ) ; return true ; } catch ( Exception e ) { return false ; }


signature:
public class CacheBuilder { /** * Constructs a new { @ code CacheBuilder } instance with the settings specified in { @ code spec } .
 * @ since 12.0 */
@ GwtIncompatible // To be supported
public static CacheBuilder < Object , Object > from ( CacheBuilderSpec spec ) { } }

implementation: return spec . toCacheBuilder ( ) . lenientParsing ( ) ;


signature:
public class CacheBuilder { /** * Sets the minimum total size for the internal hash tables . For example , if the initial capacity
 * is { @ code 60 } , and the concurrency level is { @ code 8 } , then eight segments are created , each
 * having a hash table of size eight . Providing a large enough estimate at construction time
 * avoids the need for expensive resizing operations later , but setting this value unnecessarily
 * high wastes memory .
 * @ return this { @ code CacheBuilder } instance ( for chaining )
 * @ throws IllegalArgumentException if { @ code initialCapacity } is negative
 * @ throws IllegalStateException if an initial capacity was already set */
public CacheBuilder < K , V > initialCapacity ( int initialCapacity ) { } }

implementation: checkState ( this . initialCapacity == UNSET_INT , "initial capacity was already set to %s" , this . initialCapacity ) ; checkArgument ( initialCapacity >= 0 ) ; this . initialCapacity = initialCapacity ; return this ;


signature:
public class CacheBuilder { /** * Guides the allowed concurrency among update operations . Used as a hint for internal sizing . The
 * table is internally partitioned to try to permit the indicated number of concurrent updates
 * without contention . Because assignment of entries to these partitions is not necessarily
 * uniform , the actual concurrency observed may vary . Ideally , you should choose a value to
 * accommodate as many threads as will ever concurrently modify the table . Using a significantly
 * higher value than you need can waste space and time , and a significantly lower value can lead
 * to thread contention . But overestimates and underestimates within an order of magnitude do not
 * usually have much noticeable impact . A value of one permits only one thread to modify the cache
 * at a time , but since read operations and cache loading computations can proceed concurrently ,
 * this still yields higher concurrency than full synchronization .
 * < p > Defaults to 4 . < b > Note : < / b > The default may change in the future . If you care about this
 * value , you should always choose it explicitly .
 * < p > The current implementation uses the concurrency level to create a fixed number of hashtable
 * segments , each governed by its own write lock . The segment lock is taken once for each explicit
 * write , and twice for each cache loading computation ( once prior to loading the new value , and
 * once after loading completes ) . Much internal cache management is performed at the segment
 * granularity . For example , access queues and write queues are kept per segment when they are
 * required by the selected eviction algorithm . As such , when writing unit tests it is not
 * uncommon to specify { @ code concurrencyLevel ( 1 ) } in order to achieve more deterministic eviction
 * behavior .
 * < p > Note that future implementations may abandon segment locking in favor of more advanced
 * concurrency controls .
 * @ return this { @ code CacheBuilder } instance ( for chaining )
 * @ throws IllegalArgumentException if { @ code concurrencyLevel } is nonpositive
 * @ throws IllegalStateException if a concurrency level was already set */
public CacheBuilder < K , V > concurrencyLevel ( int concurrencyLevel ) { } }

implementation: checkState ( this . concurrencyLevel == UNSET_INT , "concurrency level was already set to %s" , this . concurrencyLevel ) ; checkArgument ( concurrencyLevel > 0 ) ; this . concurrencyLevel = concurrencyLevel ; return this ;


signature:
public class CacheBuilder { /** * Specifies the maximum weight of entries the cache may contain . Weight is determined using the
 * { @ link Weigher } specified with { @ link # weigher } , and use of this method requires a
 * corresponding call to { @ link # weigher } prior to calling { @ link # build } .
 * < p > Note that the cache < b > may evict an entry before this limit is exceeded < / b > . For example , in
 * the current implementation , when { @ code concurrencyLevel } is greater than { @ code 1 } , each
 * resulting segment inside the cache < i > independently < / i > limits its own weight to approximately
 * { @ code maximumWeight / concurrencyLevel } .
 * < p > When eviction is necessary , the cache evicts entries that are less likely to be used again .
 * For example , the cache may evict an entry because it hasn ' t been used recently or very often .
 * < p > If { @ code maximumWeight } is zero , elements will be evicted immediately after being loaded
 * into cache . This can be useful in testing , or to disable caching temporarily .
 * < p > Note that weight is only used to determine whether the cache is over capacity ; it has no
 * effect on selecting which entry should be evicted next .
 * < p > This feature cannot be used in conjunction with { @ link # maximumSize } .
 * @ param maximumWeight the maximum total weight of entries the cache may contain
 * @ return this { @ code CacheBuilder } instance ( for chaining )
 * @ throws IllegalArgumentException if { @ code maximumWeight } is negative
 * @ throws IllegalStateException if a maximum weight or size was already set
 * @ since 11.0 */
@ GwtIncompatible // To be supported
public CacheBuilder < K , V > maximumWeight ( long maximumWeight ) { } }

implementation: checkState ( this . maximumWeight == UNSET_INT , "maximum weight was already set to %s" , this . maximumWeight ) ; checkState ( this . maximumSize == UNSET_INT , "maximum size was already set to %s" , this . maximumSize ) ; this . maximumWeight = maximumWeight ; checkArgument ( maximumWeight >= 0 , "maximum weight must not be negative" ) ; return this ;