signature:
public class Maps { /** * Views a function as an entry transformer that ignores the entry key . */
static < K , V1 , V2 > EntryTransformer < K , V1 , V2 > asEntryTransformer ( final Function < ? super V1 , V2 > function ) { } }

implementation: checkNotNull ( function ) ; return new EntryTransformer < K , V1 , V2 > ( ) { @ Override public V2 transformEntry ( K key , V1 value ) { return function . apply ( value ) ; } } ;


signature:
public class Maps { /** * Views an entry transformer as a function from { @ code Entry } to values . */
static < K , V1 , V2 > Function < Entry < K , V1 > , V2 > asEntryToValueFunction ( final EntryTransformer < ? super K , ? super V1 , V2 > transformer ) { } }

implementation: checkNotNull ( transformer ) ; return new Function < Entry < K , V1 > , V2 > ( ) { @ Override public V2 apply ( Entry < K , V1 > entry ) { return transformer . transformEntry ( entry . getKey ( ) , entry . getValue ( ) ) ; } } ;


signature:
public class Maps { /** * Returns a view of an entry transformed by the specified transformer . */
static < V2 , K , V1 > Entry < K , V2 > transformEntry ( final EntryTransformer < ? super K , ? super V1 , V2 > transformer , final Entry < K , V1 > entry ) { } }

implementation: checkNotNull ( transformer ) ; checkNotNull ( entry ) ; return new AbstractMapEntry < K , V2 > ( ) { @ Override public K getKey ( ) { return entry . getKey ( ) ; } @ Override public V2 getValue ( ) { return transformer . transformEntry ( entry . getKey ( ) , entry . getValue ( ) ) ; } } ;


signature:
public class Maps { /** * Views an entry transformer as a function from entries to entries . */
static < K , V1 , V2 > Function < Entry < K , V1 > , Entry < K , V2 > > asEntryToEntryFunction ( final EntryTransformer < ? super K , ? super V1 , V2 > transformer ) { } }

implementation: checkNotNull ( transformer ) ; return new Function < Entry < K , V1 > , Entry < K , V2 > > ( ) { @ Override public Entry < K , V2 > apply ( final Entry < K , V1 > entry ) { return transformEntry ( transformer , entry ) ; } } ;


signature:
public class Maps { /** * Returns a map containing the mappings in { @ code unfiltered } whose keys satisfy a predicate . The
 * returned map is a live view of { @ code unfiltered } ; changes to one affect the other .
 * < p > The resulting map ' s { @ code keySet ( ) } , { @ code entrySet ( ) } , and { @ code values ( ) } views have
 * iterators that don ' t support { @ code remove ( ) } , but all other methods are supported by the map
 * and its views . When given a key that doesn ' t satisfy the predicate , the map ' s { @ code put ( ) } and
 * { @ code putAll ( ) } methods throw an { @ link IllegalArgumentException } .
 * < p > When methods such as { @ code removeAll ( ) } and { @ code clear ( ) } are called on the filtered map
 * or its views , only mappings whose keys satisfy the filter will be removed from the underlying
 * map .
 * < p > The returned map isn ' t threadsafe or serializable , even if { @ code unfiltered } is .
 * < p > Many of the filtered map ' s methods , such as { @ code size ( ) } , iterate across every key / value
 * mapping in the underlying map and determine which satisfy the filter . When a live view is
 * < i > not < / i > needed , it may be faster to copy the filtered map and use the copy .
 * < p > < b > Warning : < / b > { @ code keyPredicate } must be < i > consistent with equals < / i > , as documented at
 * { @ link Predicate # apply } . Do not provide a predicate such as { @ code
 * Predicates . instanceOf ( ArrayList . class ) } , which is inconsistent with equals . */
public static < K , V > Map < K , V > filterKeys ( Map < K , V > unfiltered , final Predicate < ? super K > keyPredicate ) { } }

implementation: checkNotNull ( keyPredicate ) ; Predicate < Entry < K , ? > > entryPredicate = keyPredicateOnEntries ( keyPredicate ) ; return ( unfiltered instanceof AbstractFilteredMap ) ? filterFiltered ( ( AbstractFilteredMap < K , V > ) unfiltered , entryPredicate ) : new FilteredKeyMap < K , V > ( checkNotNull ( unfiltered ) , keyPredicate , entryPredicate ) ;


signature:
public class Maps { /** * Returns a sorted map containing the mappings in { @ code unfiltered } whose keys satisfy a
 * predicate . The returned map is a live view of { @ code unfiltered } ; changes to one affect the
 * other .
 * < p > The resulting map ' s { @ code keySet ( ) } , { @ code entrySet ( ) } , and { @ code values ( ) } views have
 * iterators that don ' t support { @ code remove ( ) } , but all other methods are supported by the map
 * and its views . When given a key that doesn ' t satisfy the predicate , the map ' s { @ code put ( ) } and
 * { @ code putAll ( ) } methods throw an { @ link IllegalArgumentException } .
 * < p > When methods such as { @ code removeAll ( ) } and { @ code clear ( ) } are called on the filtered map
 * or its views , only mappings whose keys satisfy the filter will be removed from the underlying
 * map .
 * < p > The returned map isn ' t threadsafe or serializable , even if { @ code unfiltered } is .
 * < p > Many of the filtered map ' s methods , such as { @ code size ( ) } , iterate across every key / value
 * mapping in the underlying map and determine which satisfy the filter . When a live view is
 * < i > not < / i > needed , it may be faster to copy the filtered map and use the copy .
 * < p > < b > Warning : < / b > { @ code keyPredicate } must be < i > consistent with equals < / i > , as documented at
 * { @ link Predicate # apply } . Do not provide a predicate such as { @ code
 * Predicates . instanceOf ( ArrayList . class ) } , which is inconsistent with equals .
 * @ since 11.0 */
public static < K , V > SortedMap < K , V > filterKeys ( SortedMap < K , V > unfiltered , final Predicate < ? super K > keyPredicate ) { } }

implementation:
// TODO ( lowasser ) : Return a subclass of Maps . FilteredKeyMap for slightly better
// performance .
return filterEntries ( unfiltered , Maps . < K > keyPredicateOnEntries ( keyPredicate ) ) ;


signature:
public class Maps { /** * Returns a bimap containing the mappings in { @ code unfiltered } whose keys satisfy a predicate .
 * The returned bimap is a live view of { @ code unfiltered } ; changes to one affect the other .
 * < p > The resulting bimap ' s { @ code keySet ( ) } , { @ code entrySet ( ) } , and { @ code values ( ) } views have
 * iterators that don ' t support { @ code remove ( ) } , but all other methods are supported by the bimap
 * and its views . When given a key that doesn ' t satisfy the predicate , the bimap ' s { @ code put ( ) } ,
 * { @ code forcePut ( ) } and { @ code putAll ( ) } methods throw an { @ link IllegalArgumentException } .
 * < p > When methods such as { @ code removeAll ( ) } and { @ code clear ( ) } are called on the filtered
 * bimap or its views , only mappings that satisfy the filter will be removed from the underlying
 * bimap .
 * < p > The returned bimap isn ' t threadsafe or serializable , even if { @ code unfiltered } is .
 * < p > Many of the filtered bimap ' s methods , such as { @ code size ( ) } , iterate across every key in
 * the underlying bimap and determine which satisfy the filter . When a live view is < i > not < / i >
 * needed , it may be faster to copy the filtered bimap and use the copy .
 * < p > < b > Warning : < / b > { @ code entryPredicate } must be < i > consistent with equals < / i > , as documented
 * at { @ link Predicate # apply } .
 * @ since 14.0 */
public static < K , V > BiMap < K , V > filterKeys ( BiMap < K , V > unfiltered , final Predicate < ? super K > keyPredicate ) { } }

implementation: checkNotNull ( keyPredicate ) ; return filterEntries ( unfiltered , Maps . < K > keyPredicateOnEntries ( keyPredicate ) ) ;


signature:
public class Maps { /** * Returns a sorted map containing the mappings in { @ code unfiltered } whose values satisfy a
 * predicate . The returned map is a live view of { @ code unfiltered } ; changes to one affect the
 * other .
 * < p > The resulting map ' s { @ code keySet ( ) } , { @ code entrySet ( ) } , and { @ code values ( ) } views have
 * iterators that don ' t support { @ code remove ( ) } , but all other methods are supported by the map
 * and its views . When given a value that doesn ' t satisfy the predicate , the map ' s { @ code put ( ) } ,
 * { @ code putAll ( ) } , and { @ link Entry # setValue } methods throw an { @ link IllegalArgumentException } .
 * < p > When methods such as { @ code removeAll ( ) } and { @ code clear ( ) } are called on the filtered map
 * or its views , only mappings whose values satisfy the filter will be removed from the underlying
 * map .
 * < p > The returned map isn ' t threadsafe or serializable , even if { @ code unfiltered } is .
 * < p > Many of the filtered map ' s methods , such as { @ code size ( ) } , iterate across every key / value
 * mapping in the underlying map and determine which satisfy the filter . When a live view is
 * < i > not < / i > needed , it may be faster to copy the filtered map and use the copy .
 * < p > < b > Warning : < / b > { @ code valuePredicate } must be < i > consistent with equals < / i > , as documented
 * at { @ link Predicate # apply } . Do not provide a predicate such as { @ code
 * Predicates . instanceOf ( ArrayList . class ) } , which is inconsistent with equals .
 * @ since 11.0 */
public static < K , V > SortedMap < K , V > filterValues ( SortedMap < K , V > unfiltered , final Predicate < ? super V > valuePredicate ) { } }

implementation: return filterEntries ( unfiltered , Maps . < V > valuePredicateOnEntries ( valuePredicate ) ) ;


signature:
public class Maps { /** * Returns a navigable map containing the mappings in { @ code unfiltered } whose values satisfy a
 * predicate . The returned map is a live view of { @ code unfiltered } ; changes to one affect the
 * other .
 * < p > The resulting map ' s { @ code keySet ( ) } , { @ code entrySet ( ) } , and { @ code values ( ) } views have
 * iterators that don ' t support { @ code remove ( ) } , but all other methods are supported by the map
 * and its views . When given a value that doesn ' t satisfy the predicate , the map ' s { @ code put ( ) } ,
 * { @ code putAll ( ) } , and { @ link Entry # setValue } methods throw an { @ link IllegalArgumentException } .
 * < p > When methods such as { @ code removeAll ( ) } and { @ code clear ( ) } are called on the filtered map
 * or its views , only mappings whose values satisfy the filter will be removed from the underlying
 * map .
 * < p > The returned map isn ' t threadsafe or serializable , even if { @ code unfiltered } is .
 * < p > Many of the filtered map ' s methods , such as { @ code size ( ) } , iterate across every key / value
 * mapping in the underlying map and determine which satisfy the filter . When a live view is
 * < i > not < / i > needed , it may be faster to copy the filtered map and use the copy .
 * < p > < b > Warning : < / b > { @ code valuePredicate } must be < i > consistent with equals < / i > , as documented
 * at { @ link Predicate # apply } . Do not provide a predicate such as { @ code
 * Predicates . instanceOf ( ArrayList . class ) } , which is inconsistent with equals .
 * @ since 14.0 */
@ GwtIncompatible // NavigableMap
public static < K , V > NavigableMap < K , V > filterValues ( NavigableMap < K , V > unfiltered , final Predicate < ? super V > valuePredicate ) { } }


signature:
public class Maps { /** * Returns a map containing the mappings in { @ code unfiltered } that satisfy a predicate . The
 * returned map is a live view of { @ code unfiltered } ; changes to one affect the other .
 * < p > The resulting map ' s { @ code keySet ( ) } , { @ code entrySet ( ) } , and { @ code values ( ) } views have
 * iterators that don ' t support { @ code remove ( ) } , but all other methods are supported by the map
 * and its views . When given a key / value pair that doesn ' t satisfy the predicate , the map ' s { @ code
 * put ( ) } and { @ code putAll ( ) } methods throw an { @ link IllegalArgumentException } . Similarly , the
 * map ' s entries have a { @ link Entry # setValue } method that throws an { @ link
 * IllegalArgumentException } when the existing key and the provided value don ' t satisfy the
 * predicate .
 * < p > When methods such as { @ code removeAll ( ) } and { @ code clear ( ) } are called on the filtered map
 * or its views , only mappings that satisfy the filter will be removed from the underlying map .
 * < p > The returned map isn ' t threadsafe or serializable , even if { @ code unfiltered } is .
 * < p > Many of the filtered map ' s methods , such as { @ code size ( ) } , iterate across every key / value
 * mapping in the underlying map and determine which satisfy the filter . When a live view is
 * < i > not < / i > needed , it may be faster to copy the filtered map and use the copy .
 * < p > < b > Warning : < / b > { @ code entryPredicate } must be < i > consistent with equals < / i > , as documented
 * at { @ link Predicate # apply } . */
public static < K , V > Map < K , V > filterEntries ( Map < K , V > unfiltered , Predicate < ? super Entry < K , V > > entryPredicate ) { } }

implementation: checkNotNull ( entryPredicate ) ; return ( unfiltered instanceof AbstractFilteredMap ) ? filterFiltered ( ( AbstractFilteredMap < K , V > ) unfiltered , entryPredicate ) : new FilteredEntryMap < K , V > ( checkNotNull ( unfiltered ) , entryPredicate ) ;


signature:
public class Maps { /** * Returns a sorted map containing the mappings in { @ code unfiltered } that satisfy a predicate .
 * The returned map is a live view of { @ code unfiltered } ; changes to one affect the other .
 * < p > The resulting map ' s { @ code keySet ( ) } , { @ code entrySet ( ) } , and { @ code values ( ) } views have
 * iterators that don ' t support { @ code remove ( ) } , but all other methods are supported by the map
 * and its views . When given a key / value pair that doesn ' t satisfy the predicate , the map ' s { @ code
 * put ( ) } and { @ code putAll ( ) } methods throw an { @ link IllegalArgumentException } . Similarly , the
 * map ' s entries have a { @ link Entry # setValue } method that throws an { @ link
 * IllegalArgumentException } when the existing key and the provided value don ' t satisfy the
 * predicate .
 * < p > When methods such as { @ code removeAll ( ) } and { @ code clear ( ) } are called on the filtered map
 * or its views , only mappings that satisfy the filter will be removed from the underlying map .
 * < p > The returned map isn ' t threadsafe or serializable , even if { @ code unfiltered } is .
 * < p > Many of the filtered map ' s methods , such as { @ code size ( ) } , iterate across every key / value
 * mapping in the underlying map and determine which satisfy the filter . When a live view is
 * < i > not < / i > needed , it may be faster to copy the filtered map and use the copy .
 * < p > < b > Warning : < / b > { @ code entryPredicate } must be < i > consistent with equals < / i > , as documented
 * at { @ link Predicate # apply } .
 * @ since 11.0 */
public static < K , V > SortedMap < K , V > filterEntries ( SortedMap < K , V > unfiltered , Predicate < ? super Entry < K , V > > entryPredicate ) { } }

implementation: checkNotNull ( entryPredicate ) ; return ( unfiltered instanceof FilteredEntrySortedMap ) ? filterFiltered ( ( FilteredEntrySortedMap < K , V > ) unfiltered , entryPredicate ) : new FilteredEntrySortedMap < K , V > ( checkNotNull ( unfiltered ) , entryPredicate ) ;


signature:
public class Maps { /** * Returns a sorted map containing the mappings in { @ code unfiltered } that satisfy a predicate .
 * The returned map is a live view of { @ code unfiltered } ; changes to one affect the other .
 * < p > The resulting map ' s { @ code keySet ( ) } , { @ code entrySet ( ) } , and { @ code values ( ) } views have
 * iterators that don ' t support { @ code remove ( ) } , but all other methods are supported by the map
 * and its views . When given a key / value pair that doesn ' t satisfy the predicate , the map ' s { @ code
 * put ( ) } and { @ code putAll ( ) } methods throw an { @ link IllegalArgumentException } . Similarly , the
 * map ' s entries have a { @ link Entry # setValue } method that throws an { @ link
 * IllegalArgumentException } when the existing key and the provided value don ' t satisfy the
 * predicate .
 * < p > When methods such as { @ code removeAll ( ) } and { @ code clear ( ) } are called on the filtered map
 * or its views , only mappings that satisfy the filter will be removed from the underlying map .
 * < p > The returned map isn ' t threadsafe or serializable , even if { @ code unfiltered } is .
 * < p > Many of the filtered map ' s methods , such as { @ code size ( ) } , iterate across every key / value
 * mapping in the underlying map and determine which satisfy the filter . When a live view is
 * < i > not < / i > needed , it may be faster to copy the filtered map and use the copy .
 * < p > < b > Warning : < / b > { @ code entryPredicate } must be < i > consistent with equals < / i > , as documented
 * at { @ link Predicate # apply } .
 * @ since 14.0 */
@ GwtIncompatible // NavigableMap
public static < K , V > NavigableMap < K , V > filterEntries ( NavigableMap < K , V > unfiltered , Predicate < ? super Entry < K , V > > entryPredicate ) { } }

implementation: checkNotNull ( entryPredicate ) ; return ( unfiltered instanceof FilteredEntryNavigableMap ) ? filterFiltered ( ( FilteredEntryNavigableMap < K , V > ) unfiltered , entryPredicate ) : new FilteredEntryNavigableMap < K , V > ( checkNotNull ( unfiltered ) , entryPredicate ) ;


signature:
public class Maps { /** * Returns a bimap containing the mappings in { @ code unfiltered } that satisfy a predicate . The
 * returned bimap is a live view of { @ code unfiltered } ; changes to one affect the other .
 * < p > The resulting bimap ' s { @ code keySet ( ) } , { @ code entrySet ( ) } , and { @ code values ( ) } views have
 * iterators that don ' t support { @ code remove ( ) } , but all other methods are supported by the bimap
 * and its views . When given a key / value pair that doesn ' t satisfy the predicate , the bimap ' s
 * { @ code put ( ) } , { @ code forcePut ( ) } and { @ code putAll ( ) } methods throw an { @ link
 * IllegalArgumentException } . Similarly , the map ' s entries have an { @ link Entry # setValue } method
 * that throws an { @ link IllegalArgumentException } when the existing key and the provided value
 * don ' t satisfy the predicate .
 * < p > When methods such as { @ code removeAll ( ) } and { @ code clear ( ) } are called on the filtered
 * bimap or its views , only mappings that satisfy the filter will be removed from the underlying
 * bimap .
 * < p > The returned bimap isn ' t threadsafe or serializable , even if { @ code unfiltered } is .
 * < p > Many of the filtered bimap ' s methods , such as { @ code size ( ) } , iterate across every key / value
 * mapping in the underlying bimap and determine which satisfy the filter . When a live view is
 * < i > not < / i > needed , it may be faster to copy the filtered bimap and use the copy .
 * < p > < b > Warning : < / b > { @ code entryPredicate } must be < i > consistent with equals < / i > , as documented
 * at { @ link Predicate # apply } .
 * @ since 14.0 */
public static < K , V > BiMap < K , V > filterEntries ( BiMap < K , V > unfiltered , Predicate < ? super Entry < K , V > > entryPredicate ) { } }

implementation: checkNotNull ( unfiltered ) ; checkNotNull ( entryPredicate ) ; return ( unfiltered instanceof FilteredEntryBiMap ) ? filterFiltered ( ( FilteredEntryBiMap < K , V > ) unfiltered , entryPredicate ) : new FilteredEntryBiMap < K , V > ( unfiltered , entryPredicate ) ;


signature:
public class Maps { /** * Support { @ code clear ( ) } , { @ code removeAll ( ) } , and { @ code retainAll ( ) } when filtering a filtered
 * map . */
private static < K , V > Map < K , V > filterFiltered ( AbstractFilteredMap < K , V > map , Predicate < ? super Entry < K , V > > entryPredicate ) { } }

implementation: return new FilteredEntryMap < > ( map . unfiltered , Predicates . < Entry < K , V > > and ( map . predicate , entryPredicate ) ) ;


signature:
public class Maps { /** * Delegates to { @ link Map # remove } . Returns { @ code null } on { @ code ClassCastException } and { @ code
 * NullPointerException } . */
static < V > V safeRemove ( Map < ? , V > map , Object key ) { } }

implementation: checkNotNull ( map ) ; try { return map . remove ( key ) ; } catch ( ClassCastException | NullPointerException e ) { return null ; }


signature:
public class Maps { /** * An admittedly inefficient implementation of { @ link Map # containsKey } . */
static boolean containsKeyImpl ( Map < ? , ? > map , @ NullableDecl Object key ) { } }

implementation: return Iterators . contains ( keyIterator ( map . entrySet ( ) . iterator ( ) ) , key ) ;


signature:
public class Maps { /** * An implementation of { @ link Map # containsValue } . */
static boolean containsValueImpl ( Map < ? , ? > map , @ NullableDecl Object value ) { } }

implementation: return Iterators . contains ( valueIterator ( map . entrySet ( ) . iterator ( ) ) , value ) ;


signature:
public class Maps { /** * Implements { @ code Collection . contains } safely for forwarding collections of map entries . If
 * { @ code o } is an instance of { @ code Entry } , it is wrapped using { @ link # unmodifiableEntry } to
 * protect against a possible nefarious equals method .
 * < p > Note that { @ code c } is the backing ( delegate ) collection , rather than the forwarding
 * collection .
 * @ param c the delegate ( unwrapped ) collection of map entries
 * @ param o the object that might be contained in { @ code c }
 * @ return { @ code true } if { @ code c } contains { @ code o } */
static < K , V > boolean containsEntryImpl ( Collection < Entry < K , V > > c , Object o ) { } }

implementation: if ( ! ( o instanceof Entry ) ) { return false ; } return c . contains ( unmodifiableEntry ( ( Entry < ? , ? > ) o ) ) ;


signature:
public class Maps { /** * Implements { @ code Collection . remove } safely for forwarding collections of map entries . If
 * { @ code o } is an instance of { @ code Entry } , it is wrapped using { @ link # unmodifiableEntry } to
 * protect against a possible nefarious equals method .
 * < p > Note that { @ code c } is backing ( delegate ) collection , rather than the forwarding collection .
 * @ param c the delegate ( unwrapped ) collection of map entries
 * @ param o the object to remove from { @ code c }
 * @ return { @ code true } if { @ code c } was changed */
static < K , V > boolean removeEntryImpl ( Collection < Entry < K , V > > c , Object o ) { } }

implementation: if ( ! ( o instanceof Entry ) ) { return false ; } return c . remove ( unmodifiableEntry ( ( Entry < ? , ? > ) o ) ) ;


signature:
public class Maps { /** * An implementation of { @ link Map # equals } . */
static boolean equalsImpl ( Map < ? , ? > map , Object object ) { } }

implementation: if ( map == object ) { return true ; } else if ( object instanceof Map ) { Map < ? , ? > o = ( Map < ? , ? > ) object ; return map . entrySet ( ) . equals ( o . entrySet ( ) ) ; } return false ;


signature:
public class Maps { /** * An implementation of { @ link Map # toString } . */
static String toStringImpl ( Map < ? , ? > map ) { } }

implementation: StringBuilder sb = Collections2 . newStringBuilderForCollection ( map . size ( ) ) . append ( '{' ) ; boolean first = true ; for ( Entry < ? , ? > entry : map . entrySet ( ) ) { if ( ! first ) { sb . append ( ", " ) ; } first = false ; sb . append ( entry . getKey ( ) ) . append ( '=' ) . append ( entry . getValue ( ) ) ; } return sb . append ( '}' ) . toString ( ) ;


signature:
public class Maps { /** * Returns a map from the ith element of list to i . */
static < E > ImmutableMap < E , Integer > indexMap ( Collection < E > list ) { } }

implementation: ImmutableMap . Builder < E , Integer > builder = new ImmutableMap . Builder < > ( list . size ( ) ) ; int i = 0 ; for ( E e : list ) { builder . put ( e , i ++ ) ; } return builder . build ( ) ;


signature:
public class Maps { /** * Returns a view of the portion of { @ code map } whose keys are contained by { @ code range } .
 * < p > This method delegates to the appropriate methods of { @ link NavigableMap } ( namely { @ link
 * NavigableMap # subMap ( Object , boolean , Object , boolean ) subMap ( ) } , { @ link
 * NavigableMap # tailMap ( Object , boolean ) tailMap ( ) } , and { @ link NavigableMap # headMap ( Object ,
 * boolean ) headMap ( ) } ) 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 NavigableMap } 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 maps can lead to unexpected and undefined behavior .
 * @ since 20.0 */
@ Beta @ GwtIncompatible // NavigableMap
public static < K extends Comparable < ? super K > , V > NavigableMap < K , V > subMap ( NavigableMap < K , V > map , Range < K > range ) { } }

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


signature:
public class Callables { /** * Creates a { @ code Callable } which immediately returns a preset value each time it is called . */
public static < T > Callable < T > returning ( @ NullableDecl final T value ) { } }

implementation: return new Callable < T > ( ) { @ Override public T call ( ) { return value ; } } ;


signature:
public class AtomicLongMap { /** * Creates an { @ code AtomicLongMap } with the same mappings as the specified { @ code Map } . */
public static < K > AtomicLongMap < K > create ( Map < ? extends K , ? extends Long > m ) { } }

implementation: AtomicLongMap < K > result = create ( ) ; result . putAll ( m ) ; return result ;


signature:
public class AtomicLongMap { /** * Adds { @ code delta } to the value currently associated with { @ code key } , and returns the new
 * value . */
@ CanIgnoreReturnValue public long addAndGet ( K key , long delta ) { } }

implementation: return accumulateAndGet ( key , delta , Long :: sum ) ;


signature:
public class AtomicLongMap { /** * Adds { @ code delta } to the value currently associated with { @ code key } , and returns the old
 * value . */
@ CanIgnoreReturnValue public long getAndAdd ( K key , long delta ) { } }

implementation: return getAndAccumulate ( key , delta , Long :: sum ) ;


signature:
public class AtomicLongMap { /** * Updates the value currently associated with { @ code key } with the specified function , and
 * returns the new value . If there is not currently a value associated with { @ code key } , the
 * function is applied to { @ code 0L } .
 * @ since 21.0 */
@ CanIgnoreReturnValue public long updateAndGet ( K key , LongUnaryOperator updaterFunction ) { } }

implementation: checkNotNull ( updaterFunction ) ; return map . compute ( key , ( k , value ) -> updaterFunction . applyAsLong ( ( value == null ) ? 0L : value . longValue ( ) ) ) ;


signature:
public class AtomicLongMap { /** * Updates the value currently associated with { @ code key } with the specified function , and
 * returns the old value . If there is not currently a value associated with { @ code key } , the
 * function is applied to { @ code 0L } .
 * @ since 21.0 */
@ CanIgnoreReturnValue public long getAndUpdate ( K key , LongUnaryOperator updaterFunction ) { } }

implementation: checkNotNull ( updaterFunction ) ; AtomicLong holder = new AtomicLong ( ) ; map . compute ( key , ( k , value ) -> { long oldValue = ( value == null ) ? 0L : value . longValue ( ) ; holder . set ( oldValue ) ; return updaterFunction . applyAsLong ( oldValue ) ; } ) ; return holder . get ( ) ;


signature:
public class AtomicLongMap { /** * Updates the value currently associated with { @ code key } by combining it with { @ code x } via the
 * specified accumulator function , returning the new value . The previous value associated with
 * { @ code key } ( or zero , if there is none ) is passed as the first argument to { @ code
 * accumulatorFunction } , and { @ code x } is passed as the second argument .
 * @ since 21.0 */
@ CanIgnoreReturnValue public long accumulateAndGet ( K key , long x , LongBinaryOperator accumulatorFunction ) { } }

implementation: checkNotNull ( accumulatorFunction ) ; return updateAndGet ( key , oldValue -> accumulatorFunction . applyAsLong ( oldValue , x ) ) ;


signature:
public class AtomicLongMap { /** * Updates the value currently associated with { @ code key } by combining it with { @ code x } via the
 * specified accumulator function , returning the old value . The previous value associated with
 * { @ code key } ( or zero , if there is none ) is passed as the first argument to { @ code
 * accumulatorFunction } , and { @ code x } is passed as the second argument .
 * @ since 21.0 */
@ CanIgnoreReturnValue public long getAndAccumulate ( K key , long x , LongBinaryOperator accumulatorFunction ) { } }

implementation: checkNotNull ( accumulatorFunction ) ; return getAndUpdate ( key , oldValue -> accumulatorFunction . applyAsLong ( oldValue , x ) ) ;


signature:
public class AtomicLongMap { /** * Removes and returns the value associated with { @ code key } . If { @ code key } is not in the map ,
 * this method has no effect and returns zero . */
@ CanIgnoreReturnValue public long remove ( K key ) { } }

implementation: Long result = map . remove ( key ) ; return ( result == null ) ? 0L : result . longValue ( ) ;


signature:
public class AtomicLongMap { /** * Returns a live , read - only view of the map backing this { @ code AtomicLongMap } . */
public Map < K , Long > asMap ( ) { } }

implementation: Map < K , Long > result = asMap ; return ( result == null ) ? asMap = createAsMap ( ) : result ;


signature:
public class AtomicLongMap { /** * If { @ code key } is not already associated with a value or if { @ code key } is associated with
 * zero , associate it with { @ code newValue } . Returns the previous value associated with { @ code
 * key } , or zero if there was no mapping for { @ code key } . */
long putIfAbsent ( K key , long newValue ) { } }

implementation: AtomicBoolean noValue = new AtomicBoolean ( false ) ; Long result = map . compute ( key , ( k , oldValue ) -> { if ( oldValue == null || oldValue == 0 ) { noValue . set ( true ) ; return newValue ; } else { return oldValue ; } } ) ; return noValue . get ( ) ? 0L : result . longValue ( ) ;


signature:
public class AtomicLongMap { /** * If { @ code ( key , expectedOldValue ) } is currently in the map , this method replaces { @ code
 * expectedOldValue } with { @ code newValue } and returns true ; otherwise , this method returns false .
 * < p > If { @ code expectedOldValue } is zero , this method will succeed if { @ code ( key , zero ) } is
 * currently in the map , or if { @ code key } is not in the map at all . */
boolean replace ( K key , long expectedOldValue , long newValue ) { } }

implementation: if ( expectedOldValue == 0L ) { return putIfAbsent ( key , newValue ) == 0L ; } else { return map . replace ( key , expectedOldValue , newValue ) ; }


signature:
public class CharSink { /** * Writes the given lines of text to this sink with each line ( including the last ) terminated with
 * the given line separator .
 * @ throws IOException if an I / O error occurs while writing to this sink */
public void writeLines ( Iterable < ? extends CharSequence > lines , String lineSeparator ) throws IOException { } }

implementation:
checkNotNull ( lines ) ; checkNotNull ( lineSeparator ) ; Closer closer = Closer . create ( ) ; try { Writer out = closer . register ( openBufferedStream ( ) ) ; for ( CharSequence line : lines ) { out . append ( line ) . append ( lineSeparator ) ; } out . flush ( ) ; // https : / / code . google . com / p / guava - libraries / issues / detail ? id = 1330
} catch ( Throwable e ) { throw closer . rethrow ( e ) ; } finally { closer . close ( ) ; }


signature:
public class MapIteratorCache { /** * Internal methods ( ' protected ' is still package - visible , but treat as only subclass - visible ) */
protected V getIfCached ( @ NullableDecl Object key ) { } }

implementation:
Entry < K , V > entry = entrySetCache ; // store local reference for thread - safety
// Check cache . We use = = on purpose because it ' s cheaper and a cache miss is ok .
if ( entry != null && entry . getKey ( ) == key ) { return entry . getValue ( ) ; } return null ;


signature:
public class AbstractFuture { /** * Marks the given node as ' deleted ' ( null waiter ) and then scans the list to unlink all deleted
 * nodes . This is an O ( n ) operation in the common case ( and O ( n ^ 2 ) in the worst ) , but we are saved
 * by two things .
 * < ul >
 * < li > This is only called when a waiting thread times out or is interrupted . Both of which
 * should be rare .
 * < li > The waiters list should be very short .
 * < / ul > */
private void removeWaiter ( Waiter node ) { } }

implementation:
node . thread = null ; // mark as ' deleted '
restart : while ( true ) { Waiter pred = null ; Waiter curr = waiters ; if ( curr == Waiter . TOMBSTONE ) { return ; // give up if someone is calling complete
} Waiter succ ; while ( curr != null ) { succ = curr . next ; if ( curr . thread != null ) { // we aren ' t unlinking this node , update pred .
pred = curr ; } else if ( pred != null ) { // We are unlinking this node and it has a predecessor .
pred . next = succ ; if ( pred . thread == null ) { // We raced with another node that unlinked pred . Restart .
continue restart ; } } else if ( ! ATOMIC_HELPER . casWaiters ( this , curr , succ ) ) { // We are unlinking head
continue restart ; // We raced with an add or complete
} curr = succ ; } break ; }


signature:
public class AbstractFuture { /** * { @ inheritDoc }
 * < p > The default { @ link AbstractFuture } implementation throws { @ code InterruptedException } if the
 * current thread is interrupted during the call , even if the value is already available .
 * @ throws CancellationException { @ inheritDoc } */
@ CanIgnoreReturnValue @ Override public V get ( long timeout , TimeUnit unit ) throws InterruptedException , TimeoutException , ExecutionException { } }

implementation:
// NOTE : if timeout < 0 , remainingNanos will be < 0 and we will fall into the while ( true ) loop
// at the bottom and throw a timeoutexception .
final long timeoutNanos = unit . toNanos ( timeout ) ; // we rely on the implicit null check on unit .
long remainingNanos = timeoutNanos ; if ( Thread . interrupted ( ) ) { throw new InterruptedException ( ) ; } Object localValue = value ; if ( localValue != null & ! ( localValue instanceof SetFuture ) ) { return getDoneValue ( localValue ) ; } // we delay calling nanoTime until we know we will need to either park or spin
final long endNanos = remainingNanos > 0 ? System . nanoTime ( ) + remainingNanos : 0 ; long_wait_loop : if ( remainingNanos >= SPIN_THRESHOLD_NANOS ) { Waiter oldHead = waiters ; if ( oldHead != Waiter . TOMBSTONE ) { Waiter node = new Waiter ( ) ; do { node . setNext ( oldHead ) ; if ( ATOMIC_HELPER . casWaiters ( this , oldHead , node ) ) { while ( true ) { LockSupport . parkNanos ( this , remainingNanos ) ; // Check interruption first , if we woke up due to interruption we need to honor that .
if ( Thread . interrupted ( ) ) { removeWaiter ( node ) ; throw new InterruptedException ( ) ; } // Otherwise re - read and check doneness . If we loop then it must have been a spurious
// wakeup
localValue = value ; if ( localValue != null & ! ( localValue instanceof SetFuture ) ) { return getDoneValue ( localValue ) ; } // timed out ?
remainingNanos = endNanos - System . nanoTime ( ) ; if ( remainingNanos < SPIN_THRESHOLD_NANOS ) { // Remove the waiter , one way or another we are done parking this thread .
removeWaiter ( node ) ; break long_wait_loop ; // jump down to the busy wait loop
} } } oldHead = waiters ; // re - read and loop .
} while ( oldHead != Waiter . TOMBSTONE ) ; } // re - read value , if we get here then we must have observed a TOMBSTONE while trying to add a
// waiter .
return getDoneValue ( value ) ; } // If we get here then we have remainingNanos < SPIN _ THRESHOLD _ NANOS and there is no node on the
// waiters list
while ( remainingNanos > 0 ) { localValue = value ; if ( localValue != null & ! ( localValue instanceof SetFuture ) ) { return getDoneValue ( localValue ) ; } if ( Thread . interrupted ( ) ) { throw new InterruptedException ( ) ; } remainingNanos = endNanos - System . nanoTime ( ) ; } String futureToString = toString ( ) ; final String unitString = unit . toString ( ) . toLowerCase ( Locale . ROOT ) ; String message = "Waited " + timeout + " " + unit . toString ( ) . toLowerCase ( Locale . ROOT ) ; // Only report scheduling delay if larger than our spin threshold - otherwise it ' s just noise
if ( remainingNanos + SPIN_THRESHOLD_NANOS < 0 ) { // We over - waited for our timeout .
message += " (plus " ; long overWaitNanos = - remainingNanos ; long overWaitUnits = unit . convert ( overWaitNanos , TimeUnit . NANOSECONDS ) ; long overWaitLeftoverNanos = overWaitNanos - unit . toNanos ( overWaitUnits ) ; boolean shouldShowExtraNanos = overWaitUnits == 0 || overWaitLeftoverNanos > SPIN_THRESHOLD_NANOS ; if ( overWaitUnits > 0 ) { message += overWaitUnits + " " + unitString ; if ( shouldShowExtraNanos ) { message += "," ; } message += " " ; } if ( shouldShowExtraNanos ) { message += overWaitLeftoverNanos + " nanoseconds " ; } message += "delay)" ; } // It ' s confusing to see a completed future in a timeout message ; if isDone ( ) returns false ,
// then we know it must have given a pending toString value earlier . If not , then the future
// completed after the timeout expired , and the message might be success .
if ( isDone ( ) ) { throw new TimeoutException ( message + " but future completed as timeout expired" ) ; } throw new TimeoutException ( message + " for " + futureToString ) ;


signature:
public class AbstractFuture { /** * { @ inheritDoc }
 * < p > The default { @ link AbstractFuture } implementation throws { @ code InterruptedException } if the
 * current thread is interrupted during the call , even if the value is already available .
 * @ throws CancellationException { @ inheritDoc } */
@ CanIgnoreReturnValue @ Override public V get ( ) throws InterruptedException , ExecutionException { } }

implementation:
if ( Thread . interrupted ( ) ) { throw new InterruptedException ( ) ; } Object localValue = value ; if ( localValue != null & ! ( localValue instanceof SetFuture ) ) { return getDoneValue ( localValue ) ; } Waiter oldHead = waiters ; if ( oldHead != Waiter . TOMBSTONE ) { Waiter node = new Waiter ( ) ; do { node . setNext ( oldHead ) ; if ( ATOMIC_HELPER . casWaiters ( this , oldHead , node ) ) { // we are on the stack , now wait for completion .
while ( true ) { LockSupport . park ( this ) ; // Check interruption first , if we woke up due to interruption we need to honor that .
if ( Thread . interrupted ( ) ) { removeWaiter ( node ) ; throw new InterruptedException ( ) ; } // Otherwise re - read and check doneness . If we loop then it must have been a spurious
// wakeup
localValue = value ; if ( localValue != null & ! ( localValue instanceof SetFuture ) ) { return getDoneValue ( localValue ) ; } } } oldHead = waiters ; // re - read and loop .
} while ( oldHead != Waiter . TOMBSTONE ) ; } // re - read value , if we get here then we must have observed a TOMBSTONE while trying to add a
// waiter .
return getDoneValue ( value ) ;


signature:
public class AbstractFuture { /** * Unboxes { @ code obj } . Assumes that obj is not { @ code null } or a { @ link SetFuture } . */
private V getDoneValue ( Object obj ) throws ExecutionException { } }

implementation:
// While this seems like it might be too branch - y , simple benchmarking proves it to be
// unmeasurable ( comparing done AbstractFutures with immediateFuture )
if ( obj instanceof Cancellation ) { throw cancellationExceptionWithCause ( "Task was cancelled." , ( ( Cancellation ) obj ) . cause ) ; } else if ( obj instanceof Failure ) { throw new ExecutionException ( ( ( Failure ) obj ) . exception ) ; } else if ( obj == NULL ) { return null ; } else { @ SuppressWarnings ( "unchecked" ) // this is the only other option
V asV = ( V ) obj ; return asV ; }


signature:
public class AbstractFuture { /** * { @ inheritDoc }
 * @ since 10.0 */
@ Override public void addListener ( Runnable listener , Executor executor ) { } }

implementation:
checkNotNull ( listener , "Runnable was null." ) ; checkNotNull ( executor , "Executor was null." ) ; // Checking isDone and listeners ! = TOMBSTONE may seem redundant , but our contract for
// addListener says that listeners execute ' immediate ' if the future isDone ( ) . However , our
// protocol for completing a future is to assign the value field ( which sets isDone to true ) and
// then to release waiters , followed by executing afterDone ( ) , followed by releasing listeners .
// That means that it is possible to observe that the future isDone and that your listeners
// don ' t execute ' immediately ' . By checking isDone here we avoid that .
// A corollary to all that is that we don ' t need to check isDone inside the loop because if we
// get into the loop we know that we weren ' t done when we entered and therefore we aren ' t under
// an obligation to execute ' immediately ' .
if ( ! isDone ( ) ) { Listener oldHead = listeners ; if ( oldHead != Listener . TOMBSTONE ) { Listener newNode = new Listener ( listener , executor ) ; do { newNode . next = oldHead ; if ( ATOMIC_HELPER . casListeners ( this , oldHead , newNode ) ) { return ; } oldHead = listeners ; // re - read
} while ( oldHead != Listener . TOMBSTONE ) ; } } // If we get here then the Listener TOMBSTONE was set , which means the future is done , call
// the listener .
executeListener ( listener , executor ) ;


signature:
public class AbstractFuture { /** * Sets the result of this { @ code Future } unless this { @ code Future } has already been cancelled or
 * set ( including { @ linkplain # setFuture set asynchronously } ) . When a call to this method returns ,
 * the { @ code Future } is guaranteed to be { @ linkplain # isDone done } < b > only if < / b > the call was
 * accepted ( in which case it returns { @ code true } ) . If it returns { @ code false } , the { @ code
 * Future } may have previously been set asynchronously , in which case its result may not be known
 * yet . That result , though not yet known , cannot be overridden by a call to a { @ code set * }
 * method , only by a call to { @ link # cancel } .
 * @ param value the value to be used as the result
 * @ return true if the attempt was accepted , completing the { @ code Future } */
@ CanIgnoreReturnValue protected boolean set ( @ Nullable V value ) { } }

implementation: Object valueToSet = value == null ? NULL : value ; if ( ATOMIC_HELPER . casValue ( this , null , valueToSet ) ) { complete ( this ) ; return true ; } return false ;


signature:
public class AbstractFuture { /** * Sets the failed result of this { @ code Future } unless this { @ code Future } has already been
 * cancelled or set ( including { @ linkplain # setFuture set asynchronously } ) . When a call to this
 * method returns , the { @ code Future } is guaranteed to be { @ linkplain # isDone done } < b > only if < / b >
 * the call was accepted ( in which case it returns { @ code true } ) . If it returns { @ code false } , the
 * { @ code Future } may have previously been set asynchronously , in which case its result may not be
 * known yet . That result , though not yet known , cannot be overridden by a call to a { @ code set * }
 * method , only by a call to { @ link # cancel } .
 * @ param throwable the exception to be used as the failed result
 * @ return true if the attempt was accepted , completing the { @ code Future } */
@ CanIgnoreReturnValue protected boolean setException ( Throwable throwable ) { } }

implementation: Object valueToSet = new Failure ( checkNotNull ( throwable ) ) ; if ( ATOMIC_HELPER . casValue ( this , null , valueToSet ) ) { complete ( this ) ; return true ; } return false ;


signature:
public class AbstractFuture { /** * Returns a value that satisfies the contract of the { @ link # value } field based on the state of
 * given future .
 * < p > This is approximately the inverse of { @ link # getDoneValue ( Object ) } */
private static Object getFutureValue ( ListenableFuture < ? > future ) { } }

implementation:
if ( future instanceof Trusted ) { // Break encapsulation for TrustedFuture instances since we know that subclasses cannot
// override . get ( ) ( since it is final ) and therefore this is equivalent to calling . get ( )
// and unpacking the exceptions like we do below ( just much faster because it is a single
// field read instead of a read , several branches and possibly creating exceptions ) .
Object v = ( ( AbstractFuture < ? > ) future ) . value ; if ( v instanceof Cancellation ) { // If the other future was interrupted , clear the interrupted bit while preserving the cause
// this will make it consistent with how non - trustedfutures work which cannot propagate the
// wasInterrupted bit
Cancellation c = ( Cancellation ) v ; if ( c . wasInterrupted ) { v = c . cause != null ? new Cancellation ( /* wasInterrupted = */
false , c . cause ) : Cancellation . CAUSELESS_CANCELLED ; } } return v ; } if ( future instanceof InternalFutureFailureAccess ) { Throwable throwable = InternalFutures . tryInternalFastPathGetFailure ( ( InternalFutureFailureAccess ) future ) ; if ( throwable != null ) { return new Failure ( throwable ) ; } } boolean wasCancelled = future . isCancelled ( ) ; // Don ' t allocate a CancellationException if it ' s not necessary
if ( ! GENERATE_CANCELLATION_CAUSES & wasCancelled ) { return Cancellation . CAUSELESS_CANCELLED ; } // Otherwise calculate the value by calling . get ( )
try { Object v = getUninterruptibly ( future ) ; if ( wasCancelled ) { return new Cancellation ( false , new IllegalArgumentException ( "get() did not throw CancellationException, despite reporting " + "isCancelled() == true: " + future ) ) ; } return v == null ? NULL : v ; } catch ( ExecutionException exception ) { if ( wasCancelled ) { return new Cancellation ( false , new IllegalArgumentException ( "get() did not throw CancellationException, despite reporting " + "isCancelled() == true: " + future , exception ) ) ; } return new Failure ( exception . getCause ( ) ) ; } catch ( CancellationException cancellation ) { if ( ! wasCancelled ) { return new Failure ( new IllegalArgumentException ( "get() threw CancellationException, despite reporting isCancelled() == false: " + future , cancellation ) ) ; } return new Cancellation ( false , cancellation ) ; } catch ( Throwable t ) { return new Failure ( t ) ; }


signature:
public class AbstractFuture { /** * Releases all threads in the { @ link # waiters } list , and clears the list . */
private void releaseWaiters ( ) { } }

implementation: Waiter head ; do { head = waiters ; } while ( ! ATOMIC_HELPER . casWaiters ( this , head , Waiter . TOMBSTONE ) ) ; for ( Waiter currentWaiter = head ; currentWaiter != null ; currentWaiter = currentWaiter . next ) { currentWaiter . unpark ( ) ; }


signature:
public class AbstractFuture { /** * Clears the { @ link # listeners } list and prepends its contents to { @ code onto } , least recently
 * added first . */
private Listener clearListeners ( Listener onto ) { } }

implementation:
// We need to
// 1 . atomically swap the listeners with TOMBSTONE , this is because addListener uses that to
// to synchronize with us
// 2 . reverse the linked list , because despite our rather clear contract , people depend on us
// executing listeners in the order they were added
// 3 . push all the items onto ' onto ' and return the new head of the stack
Listener head ; do { head = listeners ; } while ( ! ATOMIC_HELPER . casListeners ( this , head , Listener . TOMBSTONE ) ) ; Listener reversedList = onto ; while ( head != null ) { Listener tmp = head ; head = head . next ; tmp . next = reversedList ; reversedList = tmp ; } return reversedList ;


signature:
public class AbstractFuture { /** * Provide a human - readable explanation of why this future has not yet completed .
 * @ return null if an explanation cannot be provided because the future is done .
 * @ since 23.0 */
protected @ Nullable String pendingToString ( ) { } }

implementation: Object localValue = value ; if ( localValue instanceof SetFuture ) { return "setFuture=[" + userObjectToString ( ( ( SetFuture ) localValue ) . future ) + "]" ; } else if ( this instanceof ScheduledFuture ) { return "remaining delay=[" + ( ( ScheduledFuture ) this ) . getDelay ( TimeUnit . MILLISECONDS ) + " ms]" ; } return null ;


signature:
public class ExecutionSequencer { /** * Enqueues a task to run when the previous task ( if any ) completes .
 * < p > Cancellation does not propagate from the output future to a callable that has begun to
 * execute , but if the output future is cancelled before { @ link Callable # call ( ) } is invoked ,
 * { @ link Callable # call ( ) } will not be invoked . */
public < T > ListenableFuture < T > submit ( final Callable < T > callable , Executor executor ) { } }

implementation: checkNotNull ( callable ) ; return submitAsync ( new AsyncCallable < T > ( ) { @ Override public ListenableFuture < T > call ( ) throws Exception { return immediateFuture ( callable . call ( ) ) ; } @ Override public String toString ( ) { return callable . toString ( ) ; } } , executor ) ;


signature:
public class ExecutionSequencer { /** * Enqueues a task to run when the previous task ( if any ) completes .
 * < p > Cancellation does not propagate from the output future to the future returned from { @ code
 * callable } or a callable that has begun to execute , but if the output future is cancelled before
 * { @ link AsyncCallable # call ( ) } is invoked , { @ link AsyncCallable # call ( ) } will not be invoked . */
public < T > ListenableFuture < T > submitAsync ( final AsyncCallable < T > callable , final Executor executor ) { } }

implementation:
checkNotNull ( callable ) ; final AtomicReference < RunningState > runningState = new AtomicReference < > ( NOT_RUN ) ; final AsyncCallable < T > task = new AsyncCallable < T > ( ) { @ Override public ListenableFuture < T > call ( ) throws Exception { if ( ! runningState . compareAndSet ( NOT_RUN , STARTED ) ) { return immediateCancelledFuture ( ) ; } return callable . call ( ) ; } @ Override public String toString ( ) { return callable . toString ( ) ; } } ; /* * Four futures are at play here :
 * taskFuture is the future tracking the result of the callable .
 * newFuture is a future that completes after this and all prior tasks are done .
 * oldFuture is the previous task ' s newFuture .
 * outputFuture is the future we return to the caller , a nonCancellationPropagating taskFuture .
 * newFuture is guaranteed to only complete once all tasks previously submitted to this instance
 * have completed - namely after oldFuture is done , and taskFuture has either completed or been
 * cancelled before the callable started execution . */
final SettableFuture < Object > newFuture = SettableFuture . create ( ) ; final ListenableFuture < ? > oldFuture = ref . getAndSet ( newFuture ) ; // Invoke our task once the previous future completes .
final ListenableFuture < T > taskFuture = Futures . submitAsync ( task , new Executor ( ) { @ Override public void execute ( Runnable runnable ) { oldFuture . addListener ( runnable , executor ) ; } } ) ; final ListenableFuture < T > outputFuture = Futures . nonCancellationPropagating ( taskFuture ) ; // newFuture ' s lifetime is determined by taskFuture , which can ' t complete before oldFuture
// unless taskFuture is cancelled , in which case it falls back to oldFuture . This ensures that
// if the future we return is cancelled , we don ' t begin execution of the next task until after
// oldFuture completes .
Runnable listener = new Runnable ( ) { @ Override public void run ( ) { if ( taskFuture . isDone ( ) // If this CAS succeeds , we know that the provided callable will never be invoked ,
// so when oldFuture completes it is safe to allow the next submitted task to
// proceed .
|| ( outputFuture . isCancelled ( ) && runningState . compareAndSet ( NOT_RUN , CANCELLED ) ) ) { // Since the value of oldFuture can only ever be immediateFuture ( null ) or setFuture of
// a future that eventually came from immediateFuture ( null ) , this doesn ' t leak
// throwables or completion values .
newFuture . setFuture ( oldFuture ) ; } } } ; // Adding the listener to both futures guarantees that newFuture will aways be set . Adding to
// taskFuture guarantees completion if the callable is invoked , and adding to outputFuture
// propagates cancellation if the callable has not yet been invoked .
outputFuture . addListener ( listener , directExecutor ( ) ) ; taskFuture . addListener ( listener , directExecutor ( ) ) ; return outputFuture ;


signature:
public class Platform { /** * Returns the platform preferred implementation of a map based on a hash table . */
static < K , V > Map < K , V > newHashMapWithExpectedSize ( int expectedSize ) { } }

implementation: return CompactHashMap . createWithExpectedSize ( expectedSize ) ;


signature:
public class Platform { /** * Returns the platform preferred implementation of an insertion ordered map based on a hash
 * table . */
static < K , V > Map < K , V > newLinkedHashMapWithExpectedSize ( int expectedSize ) { } }

implementation: return CompactLinkedHashMap . createWithExpectedSize ( expectedSize ) ;


signature:
public class ImmutableLongArray { /** * Returns an immutable array containing all the values from { @ code stream } , in order . */
public static ImmutableLongArray copyOf ( LongStream stream ) { } }

implementation:
// Note this uses very different growth behavior from copyOf ( Iterable ) and the builder .
long [ ] array = stream . toArray ( ) ; return ( array . length == 0 ) ? EMPTY : new ImmutableLongArray ( array ) ;


signature:
public class Quantiles { /** * Returns a value a fraction { @ code ( remainder / scale ) } of the way between { @ code lower } and
 * { @ code upper } . Assumes that { @ code lower < = upper } . Correctly handles infinities ( but not
 * { @ code NaN } ) . */
private static double interpolate ( double lower , double upper , double remainder , double scale ) { } }

implementation:
if ( lower == NEGATIVE_INFINITY ) { if ( upper == POSITIVE_INFINITY ) { // Return NaN when lower = = NEGATIVE _ INFINITY and upper = = POSITIVE _ INFINITY :
return NaN ; } // Return NEGATIVE _ INFINITY when NEGATIVE _ INFINITY = = lower < = upper < POSITIVE _ INFINITY :
return NEGATIVE_INFINITY ; } if ( upper == POSITIVE_INFINITY ) { // Return POSITIVE _ INFINITY when NEGATIVE _ INFINITY < lower < = upper = = POSITIVE _ INFINITY :
return POSITIVE_INFINITY ; } return lower + ( upper - lower ) * remainder / scale ;


signature:
public class Quantiles { /** * Performs an in - place selection to find the element which would appear at a given index in a
 * dataset if it were sorted . The following preconditions should hold :
 * < ul >
 * < li > { @ code required } , { @ code from } , and { @ code to } should all be indexes into { @ code array } ;
 * < li > { @ code required } should be in the range [ { @ code from } , { @ code to } ] ;
 * < li > all the values with indexes in the range [ 0 , { @ code from } ) should be less than or equal
 * to all the values with indexes in the range [ { @ code from } , { @ code to } ] ;
 * < li > all the values with indexes in the range ( { @ code to } , { @ code array . length - 1 } ] should be
 * greater than or equal to all the values with indexes in the range [ { @ code from } , { @ code
 * to } ] .
 * < / ul >
 * This method will reorder the values with indexes in the range [ { @ code from } , { @ code to } ] such
 * that all the values with indexes in the range [ { @ code from } , { @ code required } ) are less than or
 * equal to the value with index { @ code required } , and all the values with indexes in the range
 * ( { @ code required } , { @ code to } ] are greater than or equal to that value . Therefore , the value at
 * { @ code required } is the value which would appear at that index in the sorted dataset . */
private static void selectInPlace ( int required , double [ ] array , int from , int to ) { } }

implementation:
// If we are looking for the least element in the range , we can just do a linear search for it .
// ( We will hit this whenever we are doing quantile interpolation : our first selection finds
// the lower value , our second one finds the upper value by looking for the next least element . )
if ( required == from ) { int min = from ; for ( int index = from + 1 ; index <= to ; index ++ ) { if ( array [ min ] > array [ index ] ) { min = index ; } } if ( min != from ) { swap ( array , min , from ) ; } return ; } // Let ' s play quickselect ! We ' ll repeatedly partition the range [ from , to ] containing the
// required element , as long as it has more than one element .
while ( to > from ) { int partitionPoint = partition ( array , from , to ) ; if ( partitionPoint >= required ) { to = partitionPoint - 1 ; } if ( partitionPoint <= required ) { from = partitionPoint + 1 ; } }


signature:
public class Quantiles { /** * Performs a partition operation on the slice of { @ code array } with elements in the range [ { @ code
 * from } , { @ code to } ] . Uses the median of { @ code from } , { @ code to } , and the midpoint between them
 * as a pivot . Returns the index which the slice is partitioned around , i . e . if it returns { @ code
 * ret } then we know that the values with indexes in [ { @ code from } , { @ code ret } ) are less than or
 * equal to the value at { @ code ret } and the values with indexes in ( { @ code ret } , { @ code to } ] are
 * greater than or equal to that . */
private static int partition ( double [ ] array , int from , int to ) { } }

implementation:
// Select a pivot , and move it to the start of the slice i . e . to index from .
movePivotToStartOfSlice ( array , from , to ) ; double pivot = array [ from ] ; // Move all elements with indexes in ( from , to ] which are greater than the pivot to the end of
// the array . Keep track of where those elements begin .
int partitionPoint = to ; for ( int i = to ; i > from ; i -- ) { if ( array [ i ] > pivot ) { swap ( array , partitionPoint , i ) ; partitionPoint -- ; } } // We now know that all elements with indexes in ( from , partitionPoint ] are less than or equal
// to the pivot at from , and all elements with indexes in ( partitionPoint , to ] are greater than
// it . We swap the pivot into partitionPoint and we know the array is partitioned around that .
swap ( array , from , partitionPoint ) ; return partitionPoint ;


signature:
public class Quantiles { /** * Selects the pivot to use , namely the median of the values at { @ code from } , { @ code to } , and
 * halfway between the two ( rounded down ) , from { @ code array } , and ensure ( by swapping elements if
 * necessary ) that that pivot value appears at the start of the slice i . e . at { @ code from } .
 * Expects that { @ code from } is strictly less than { @ code to } . */
private static void movePivotToStartOfSlice ( double [ ] array , int from , int to ) { } }

implementation:
int mid = ( from + to ) >>> 1 ; // We want to make a swap such that either array [ to ] < = array [ from ] < = array [ mid ] , or
// array [ mid ] < = array [ from ] < = array [ to ] . We know that from < to , so we know mid < to
// ( although it ' s possible that mid = = from , if to = = from + 1 ) . Note that the postcondition
// would be impossible to fulfil if mid = = to unless we also have array [ from ] = = array [ to ] .
boolean toLessThanMid = ( array [ to ] < array [ mid ] ) ; boolean midLessThanFrom = ( array [ mid ] < array [ from ] ) ; boolean toLessThanFrom = ( array [ to ] < array [ from ] ) ; if ( toLessThanMid == midLessThanFrom ) { // Either array [ to ] < array [ mid ] < array [ from ] or array [ from ] < = array [ mid ] < = array [ to ] .
swap ( array , mid , from ) ; } else if ( toLessThanMid != toLessThanFrom ) { // Either array [ from ] < = array [ to ] < array [ mid ] or array [ mid ] < = array [ to ] < array [ from ] .
swap ( array , from , to ) ; } // The postcondition now holds . So the median , our chosen pivot , is at from .


signature:
public class Quantiles { /** * Performs an in - place selection , like { @ link # selectInPlace } , to select all the indexes { @ code
 * allRequired [ i ] } for { @ code i } in the range [ { @ code requiredFrom } , { @ code requiredTo } ] . These
 * indexes must be sorted in the array and must all be in the range [ { @ code from } , { @ code to } ] . */
private static void selectAllInPlace ( int [ ] allRequired , int requiredFrom , int requiredTo , double [ ] array , int from , int to ) { } }

implementation:
// Choose the first selection to do . . .
int requiredChosen = chooseNextSelection ( allRequired , requiredFrom , requiredTo , from , to ) ; int required = allRequired [ requiredChosen ] ; // . . . do the first selection . . .
selectInPlace ( required , array , from , to ) ; // . . . then recursively perform the selections in the range below . . .
int requiredBelow = requiredChosen - 1 ; while ( requiredBelow >= requiredFrom && allRequired [ requiredBelow ] == required ) { requiredBelow -- ; // skip duplicates of required in the range below
} if ( requiredBelow >= requiredFrom ) { selectAllInPlace ( allRequired , requiredFrom , requiredBelow , array , from , required - 1 ) ; } // . . . and then recursively perform the selections in the range above .
int requiredAbove = requiredChosen + 1 ; while ( requiredAbove <= requiredTo && allRequired [ requiredAbove ] == required ) { requiredAbove ++ ; // skip duplicates of required in the range above
} if ( requiredAbove <= requiredTo ) { selectAllInPlace ( allRequired , requiredAbove , requiredTo , array , required + 1 , to ) ; }


signature:
public class Quantiles { /** * Chooses the next selection to do from the required selections . It is required that the array
 * { @ code allRequired } is sorted and that { @ code allRequired [ i ] } are in the range [ { @ code from } ,
 * { @ code to } ] for all { @ code i } in the range [ { @ code requiredFrom } , { @ code requiredTo } ] . The
 * value returned by this method is the { @ code i } in that range such that { @ code allRequired [ i ] }
 * is as close as possible to the center of the range [ { @ code from } , { @ code to } ] . Choosing the
 * value closest to the center of the range first is the most efficient strategy because it
 * minimizes the size of the subranges from which the remaining selections must be done . */
private static int chooseNextSelection ( int [ ] allRequired , int requiredFrom , int requiredTo , int from , int to ) { } }

implementation:
if ( requiredFrom == requiredTo ) { return requiredFrom ; // only one thing to choose , so choose it
} // Find the center and round down . The true center is either centerFloor or halfway between
// centerFloor and centerFloor + 1.
int centerFloor = ( from + to ) >>> 1 ; // Do a binary search until we ' re down to the range of two which encloses centerFloor ( unless
// all values are lower or higher than centerFloor , in which case we find the two highest or
// lowest respectively ) . If centerFloor is in allRequired , we will definitely find it . If not ,
// but centerFloor + 1 is , we ' ll definitely find that . The closest value to the true ( unrounded )
// center will be at either low or high .
int low = requiredFrom ; int high = requiredTo ; while ( high > low + 1 ) { int mid = ( low + high ) >>> 1 ; if ( allRequired [ mid ] > centerFloor ) { high = mid ; } else if ( allRequired [ mid ] < centerFloor ) { low = mid ; } else { return mid ; // allRequired [ mid ] = centerFloor , so we can ' t get closer than that
} } // Now pick the closest of the two candidates . Note that there is no rounding here .
if ( from + to - allRequired [ low ] - allRequired [ high ] > 0 ) { return high ; } else { return low ; }


signature:
public class StandardRowSortedTable { /** * { @ inheritDoc }
 * < p > This method returns a { @ link SortedMap } , instead of the { @ code Map } specified in the { @ link
 * Table } interface . */
@ Override public SortedMap < R , Map < C , V > > rowMap ( ) { } }

implementation: return ( SortedMap < R , Map < C , V > > ) super . rowMap ( ) ;


signature:
public class Doubles { /** * Sorts the elements of { @ code array } between { @ code fromIndex } inclusive and { @ code toIndex }
 * exclusive in descending order .
 * < p > Note that this method uses the total order imposed by { @ link Double # compare } , which treats
 * all NaN values as equal and 0.0 as greater than - 0.0.
 * @ since 23.1 */
public static void sortDescending ( double [ ] array , int fromIndex , int toIndex ) { } }

implementation: checkNotNull ( array ) ; checkPositionIndexes ( fromIndex , toIndex , array . length ) ; Arrays . sort ( array , fromIndex , toIndex ) ; reverse ( array , fromIndex , toIndex ) ;


signature:
public class Doubles { /** * Reverses the elements of { @ code array } between { @ code fromIndex } inclusive and { @ code toIndex }
 * exclusive . This is equivalent to { @ code
 * Collections . reverse ( Doubles . asList ( array ) . subList ( fromIndex , toIndex ) ) } , but is likely to be
 * more efficient .
 * @ throws IndexOutOfBoundsException if { @ code fromIndex < 0 } , { @ code toIndex > array . length } , or
 * { @ code toIndex > fromIndex }
 * @ since 23.1 */
public static void reverse ( double [ ] array , int fromIndex , int toIndex ) { } }

implementation: checkNotNull ( array ) ; checkPositionIndexes ( fromIndex , toIndex , array . length ) ; for ( int i = fromIndex , j = toIndex - 1 ; i < j ; i ++ , j -- ) { double tmp = array [ i ] ; array [ i ] = array [ j ] ; array [ j ] = tmp ; }


signature:
public class Doubles { /** * Returns an array containing each value of { @ code collection } , converted to a { @ code double }
 * value in the manner of { @ link Number # doubleValue } .
 * < p > Elements are copied from the argument collection as if by { @ code collection . toArray ( ) } .
 * Calling this method is as thread - safe as calling that method .
 * @ param collection a collection of { @ code Number } instances
 * @ return an array containing the same values as { @ code collection } , in the same order , converted
 * to primitives
 * @ throws NullPointerException if { @ code collection } or any of its elements is null
 * @ since 1.0 ( parameter was { @ code Collection < Double > } before 12.0) */
public static double [ ] toArray ( Collection < ? extends Number > collection ) { } }

implementation:
if ( collection instanceof DoubleArrayAsList ) { return ( ( DoubleArrayAsList ) collection ) . toDoubleArray ( ) ; } Object [ ] boxedArray = collection . toArray ( ) ; int len = boxedArray . length ; double [ ] array = new double [ len ] ; for ( int i = 0 ; i < len ; i ++ ) { // checkNotNull for GWT ( do not optimize )
array [ i ] = ( ( Number ) checkNotNull ( boxedArray [ i ] ) ) . doubleValue ( ) ; } return array ;


signature:
public class Doubles { /** * Returns a fixed - size list backed by the specified array , similar to { @ link
 * Arrays # asList ( Object [ ] ) } . The list supports { @ link List # set ( int , Object ) } , but any attempt to
 * set a value to { @ code null } will result in a { @ link NullPointerException } .
 * < p > The returned list maintains the values , but not the identities , of { @ code Double } objects
 * written to or read from it . For example , whether { @ code list . get ( 0 ) = = list . get ( 0 ) } is true for
 * the returned list is unspecified .
 * < p > The returned list may have unexpected behavior if it contains { @ code NaN } , or if { @ code NaN }
 * is used as a parameter to any of its methods .
 * < p > < b > Note : < / b > when possible , you should represent your data as an { @ link
 * ImmutableDoubleArray } instead , which has an { @ link ImmutableDoubleArray # asList asList } view .
 * @ param backingArray the array to back the list
 * @ return a list view of the array */
public static List < Double > asList ( double ... backingArray ) { } }

implementation: if ( backingArray . length == 0 ) { return Collections . emptyList ( ) ; } return new DoubleArrayAsList ( backingArray ) ;


signature:
public class Doubles { /** * Parses the specified string as a double - precision floating point value . The ASCII character
 * { @ code ' - ' } ( < code > ' & # 92 ; u002D ' < / code > ) is recognized as the minus sign .
 * < p > Unlike { @ link Double # parseDouble ( String ) } , this method returns { @ code null } instead of
 * throwing an exception if parsing fails . Valid inputs are exactly those accepted by { @ link
 * Double # valueOf ( String ) } , except that leading and trailing whitespace is not permitted .
 * < p > This implementation is likely to be faster than { @ code Double . parseDouble } if many failures
 * are expected .
 * @ param string the string representation of a { @ code double } value
 * @ return the floating point value represented by { @ code string } , or { @ code null } if { @ code
 * string } has a length of zero or cannot be parsed as a { @ code double } value
 * @ since 14.0 */
@ Beta @ GwtIncompatible // regular expressions
@ NullableDecl public static Double tryParse ( String string ) { } }

implementation:
if ( FLOATING_POINT_PATTERN . matcher ( string ) . matches ( ) ) { // TODO ( lowasser ) : could be potentially optimized , but only with
// extensive testing
try { return Double . parseDouble ( string ) ; } catch ( NumberFormatException e ) { // Double . parseDouble has changed specs several times , so fall through
// gracefully
} } return null ;


signature:
public class ForwardingList { /** * A sensible default implementation of { @ link # subList ( int , int ) } . If you override any other
 * methods , you may wish to override { @ link # subList ( int , int ) } to forward to this implementation .
 * @ since 7.0 */
@ Beta protected List < E > standardSubList ( int fromIndex , int toIndex ) { } }

implementation: return Lists . subListImpl ( this , fromIndex , toIndex ) ;


signature:
public class Maps { /** * Returns a { @ link Collector } that accumulates elements into an { @ code ImmutableMap } whose keys
 * and values are the result of applying the provided mapping functions to the input elements . The
 * resulting implementation is specialized for enum key types . The returned map and its views will
 * iterate over keys in their enum definition order , not encounter order .
 * < p > If the mapped keys contain duplicates , an { @ code IllegalArgumentException } is thrown when
 * the collection operation is performed . ( This differs from the { @ code Collector } returned by
 * { @ link java . util . stream . Collectors # toMap ( java . util . function . Function ,
 * java . util . function . Function ) Collectors . toMap ( Function , Function ) } , which throws an { @ code
 * IllegalStateException } . )
 * @ since 21.0 */
public static < T , K extends Enum < K > , V > Collector < T , ? , ImmutableMap < K , V > > toImmutableEnumMap ( java . util . function . Function < ? super T , ? extends K > keyFunction , java . util . function . Function < ? super T , ? extends V > valueFunction ) { } }

implementation: checkNotNull ( keyFunction ) ; checkNotNull ( valueFunction ) ; return Collector . of ( ( ) -> new Accumulator < K , V > ( ( v1 , v2 ) -> { throw new IllegalArgumentException ( "Multiple values for key: " + v1 + ", " + v2 ) ; } ) , ( accum , t ) -> { K key = checkNotNull ( keyFunction . apply ( t ) , "Null key for input %s" , t ) ; V newValue = checkNotNull ( valueFunction . apply ( t ) , "Null value for input %s" , t ) ; accum . put ( key , newValue ) ; } , Accumulator :: combine , Accumulator :: toImmutableMap , Collector . Characteristics . UNORDERED ) ;


signature:
public class Maps { /** * Returns a { @ link Collector } that accumulates elements into an { @ code ImmutableMap } whose keys
 * and values are the result of applying the provided mapping functions to the input elements . The
 * resulting implementation is specialized for enum key types . The returned map and its views will
 * iterate over keys in their enum definition order , not encounter order .
 * < p > If the mapped keys contain duplicates , the values are merged using the specified merging
 * function .
 * @ since 21.0 */
public static < T , K extends Enum < K > , V > Collector < T , ? , ImmutableMap < K , V > > toImmutableEnumMap ( java . util . function . Function < ? super T , ? extends K > keyFunction , java . util . function . Function < ? super T , ? extends V > valueFunction , BinaryOperator < V > mergeFunction ) { } }

implementation:
checkNotNull ( keyFunction ) ; checkNotNull ( valueFunction ) ; checkNotNull ( mergeFunction ) ; // not UNORDERED because we don ' t know if mergeFunction is commutative
return Collector . of ( ( ) -> new Accumulator < K , V > ( mergeFunction ) , ( accum , t ) -> { K key = checkNotNull ( keyFunction . apply ( t ) , "Null key for input %s" , t ) ; V newValue = checkNotNull ( valueFunction . apply ( t ) , "Null value for input %s" , t ) ; accum . put ( key , newValue ) ; } , Accumulator :: combine , Accumulator :: toImmutableMap ) ;


signature:
public class Maps { /** * Delegates to { @ link Map # get } . Returns { @ code null } on { @ code ClassCastException } and { @ code
 * NullPointerException } . */
static < V > V safeGet ( Map < ? , V > map , @ Nullable Object key ) { } }

implementation: checkNotNull ( map ) ; try { return map . get ( key ) ; } catch ( ClassCastException | NullPointerException e ) { return null ; }


signature:
public class Multimaps { /** * Returns a { @ code Collector } accumulating entries into a { @ code Multimap } generated from the
 * specified supplier . The keys and values of the entries are the result of applying the provided
 * mapping functions to the input elements , accumulated in the encounter order of the stream .
 * < p > Example :
 * < pre > { @ code
 * static final ListMultimap < Character , String > FIRST _ LETTER _ MULTIMAP =
 * Stream . of ( " banana " , " apple " , " carrot " , " asparagus " , " cherry " )
 * . collect (
 * toMultimap (
 * str - > str . charAt ( 0 ) ,
 * str - > str . substring ( 1 ) ,
 * MultimapBuilder . treeKeys ( ) . arrayListValues ( ) : : build ) ) ;
 * / / is equivalent to
 * static final ListMultimap < Character , String > FIRST _ LETTER _ MULTIMAP ;
 * static {
 * FIRST _ LETTER _ MULTIMAP = MultimapBuilder . treeKeys ( ) . arrayListValues ( ) . build ( ) ;
 * FIRST _ LETTER _ MULTIMAP . put ( ' b ' , " anana " ) ;
 * FIRST _ LETTER _ MULTIMAP . put ( ' a ' , " pple " ) ;
 * FIRST _ LETTER _ MULTIMAP . put ( ' a ' , " sparagus " ) ;
 * FIRST _ LETTER _ MULTIMAP . put ( ' c ' , " arrot " ) ;
 * FIRST _ LETTER _ MULTIMAP . put ( ' c ' , " herry " ) ;
 * } < / pre >
 * @ since 21.0 */
@ Beta public static < T , K , V , M extends Multimap < K , V > > Collector < T , ? , M > toMultimap ( java . util . function . Function < ? super T , ? extends K > keyFunction , java . util . function . Function < ? super T , ? extends V > valueFunction , java . util . function . Supplier < M > multimapSupplier ) { } }

implementation: checkNotNull ( keyFunction ) ; checkNotNull ( valueFunction ) ; checkNotNull ( multimapSupplier ) ; return Collector . of ( multimapSupplier , ( multimap , input ) -> multimap . put ( keyFunction . apply ( input ) , valueFunction . apply ( input ) ) , ( multimap1 , multimap2 ) -> { multimap1 . putAll ( multimap2 ) ; return multimap1 ; } ) ;


signature:
public class Multimaps { /** * Returns a { @ code Collector } accumulating entries into a { @ code Multimap } generated from the
 * specified supplier . Each input element is mapped to a key and a stream of values , each of which
 * are put into the resulting { @ code Multimap } , in the encounter order of the stream and the
 * encounter order of the streams of values .
 * < p > Example :
 * < pre > { @ code
 * static final ListMultimap < Character , Character > FIRST _ LETTER _ MULTIMAP =
 * Stream . of ( " banana " , " apple " , " carrot " , " asparagus " , " cherry " )
 * . collect (
 * flatteningToMultimap (
 * str - > str . charAt ( 0 ) ,
 * str - > str . substring ( 1 ) . chars ( ) . mapToObj ( c - > ( char ) c ) ,
 * MultimapBuilder . linkedHashKeys ( ) . arrayListValues ( ) : : build ) ) ;
 * / / is equivalent to
 * static final ListMultimap < Character , Character > FIRST _ LETTER _ MULTIMAP ;
 * static {
 * FIRST _ LETTER _ MULTIMAP = MultimapBuilder . linkedHashKeys ( ) . arrayListValues ( ) . build ( ) ;
 * FIRST _ LETTER _ MULTIMAP . putAll ( ' b ' , Arrays . asList ( ' a ' , ' n ' , ' a ' , ' n ' , ' a ' ) ) ;
 * FIRST _ LETTER _ MULTIMAP . putAll ( ' a ' , Arrays . asList ( ' p ' , ' p ' , ' l ' , ' e ' ) ) ;
 * FIRST _ LETTER _ MULTIMAP . putAll ( ' c ' , Arrays . asList ( ' a ' , ' r ' , ' r ' , ' o ' , ' t ' ) ) ;
 * FIRST _ LETTER _ MULTIMAP . putAll ( ' a ' , Arrays . asList ( ' s ' , ' p ' , ' a ' , ' r ' , ' a ' , ' g ' , ' u ' , ' s ' ) ) ;
 * FIRST _ LETTER _ MULTIMAP . putAll ( ' c ' , Arrays . asList ( ' h ' , ' e ' , ' r ' , ' r ' , ' y ' ) ) ;
 * } < / pre >
 * @ since 21.0 */
@ Beta public static < T , K , V , M extends Multimap < K , V > > Collector < T , ? , M > flatteningToMultimap ( java . util . function . Function < ? super T , ? extends K > keyFunction , java . util . function . Function < ? super T , ? extends Stream < ? extends V > > valueFunction , java . util . function . Supplier < M > multimapSupplier ) { } }

implementation: checkNotNull ( keyFunction ) ; checkNotNull ( valueFunction ) ; checkNotNull ( multimapSupplier ) ; return Collector . of ( multimapSupplier , ( multimap , input ) -> { K key = keyFunction . apply ( input ) ; Collection < V > valuesForKey = multimap . get ( key ) ; valueFunction . apply ( input ) . forEachOrdered ( valuesForKey :: add ) ; } , ( multimap1 , multimap2 ) -> { multimap1 . putAll ( multimap2 ) ; return multimap1 ; } ) ;


signature:
public class Multimaps { /** * Creates a new { @ code Multimap } backed by { @ code map } , whose internal value collections are
 * generated by { @ code factory } .
 * < p > < b > Warning : do not use < / b > this method when the collections returned by { @ code factory }
 * implement either { @ link List } or { @ code Set } ! Use the more specific method { @ link
 * # newListMultimap } , { @ link # newSetMultimap } or { @ link # newSortedSetMultimap } instead , to avoid
 * very surprising behavior from { @ link Multimap # equals } .
 * < p > The { @ code factory } - generated and { @ code map } classes determine the multimap iteration
 * order . They also specify the behavior of the { @ code equals } , { @ code hashCode } , and { @ code
 * toString } methods for the multimap and its returned views . However , the multimap ' s { @ code get }
 * method returns instances of a different class than { @ code factory . get ( ) } does .
 * < p > The multimap is serializable if { @ code map } , { @ code factory } , the collections generated by
 * { @ code factory } , and the multimap contents are all serializable .
 * < p > The multimap is not threadsafe when any concurrent operations update the multimap , even if
 * { @ code map } and the instances generated by { @ code factory } are . Concurrent read operations will
 * work correctly . To allow concurrent update operations , wrap the multimap with a call to { @ link
 * # synchronizedMultimap } .
 * < p > Call this method only when the simpler methods { @ link ArrayListMultimap # create ( ) } , { @ link
 * HashMultimap # create ( ) } , { @ link LinkedHashMultimap # create ( ) } , { @ link
 * LinkedListMultimap # create ( ) } , { @ link TreeMultimap # create ( ) } , and { @ link
 * TreeMultimap # create ( Comparator , Comparator ) } won ' t suffice .
 * < p > Note : the multimap assumes complete ownership over of { @ code map } and the collections
 * returned by { @ code factory } . Those objects should not be manually updated and they should not
 * use soft , weak , or phantom references .
 * @ param map place to store the mapping from each key to its corresponding values
 * @ param factory supplier of new , empty collections that will each hold all values for a given
 * key
 * @ throws IllegalArgumentException if { @ code map } is not empty */
public static < K , V > Multimap < K , V > newMultimap ( Map < K , Collection < V > > map , final Supplier < ? extends Collection < V > > factory ) { } }

implementation: return new CustomMultimap < > ( map , factory ) ;


signature:
public class Multimaps { /** * Creates a new { @ code SortedSetMultimap } that uses the provided map and factory . It can generate
 * a multimap based on arbitrary { @ link Map } and { @ link SortedSet } classes .
 * < p > The { @ code factory } - generated and { @ code map } classes determine the multimap iteration
 * order . They also specify the behavior of the { @ code equals } , { @ code hashCode } , and { @ code
 * toString } methods for the multimap and its returned views . However , the multimap ' s { @ code get }
 * method returns instances of a different class than { @ code factory . get ( ) } does .
 * < p > The multimap is serializable if { @ code map } , { @ code factory } , the sets generated by { @ code
 * factory } , and the multimap contents are all serializable .
 * < p > The multimap is not threadsafe when any concurrent operations update the multimap , even if
 * { @ code map } and the instances generated by { @ code factory } are . Concurrent read operations will
 * work correctly . To allow concurrent update operations , wrap the multimap with a call to { @ link
 * # synchronizedSortedSetMultimap } .
 * < p > Call this method only when the simpler methods { @ link TreeMultimap # create ( ) } and { @ link
 * TreeMultimap # create ( Comparator , Comparator ) } won ' t suffice .
 * < p > Note : the multimap assumes complete ownership over of { @ code map } and the sets returned by
 * { @ code factory } . Those objects should not be manually updated and they should not use soft ,
 * weak , or phantom references .
 * @ param map place to store the mapping from each key to its corresponding values
 * @ param factory supplier of new , empty sorted sets that will each hold all values for a given
 * key
 * @ throws IllegalArgumentException if { @ code map } is not empty */
public static < K , V > SortedSetMultimap < K , V > newSortedSetMultimap ( Map < K , Collection < V > > map , final Supplier < ? extends SortedSet < V > > factory ) { } }

implementation: return new CustomSortedSetMultimap < > ( map , factory ) ;


signature:
public class Multimaps { /** * Copies each key - value mapping in { @ code source } into { @ code dest } , with its key and value
 * reversed .
 * < p > If { @ code source } is an { @ link ImmutableMultimap } , consider using { @ link
 * ImmutableMultimap # inverse } instead .
 * @ param source any multimap
 * @ param dest the multimap to copy into ; usually empty
 * @ return { @ code dest } */
@ CanIgnoreReturnValue public static < K , V , M extends Multimap < K , V > > M invertFrom ( Multimap < ? extends V , ? extends K > source , M dest ) { } }

implementation: checkNotNull ( dest ) ; for ( Map . Entry < ? extends V , ? extends K > entry : source . entries ( ) ) { dest . put ( entry . getValue ( ) , entry . getKey ( ) ) ; } return dest ;


signature:
public class Multimaps { /** * Returns a synchronized ( thread - safe ) multimap backed by the specified multimap . In order to
 * guarantee serial access , it is critical that < b > all < / b > access to the backing multimap is
 * accomplished through the returned multimap .
 * < p > It is imperative that the user manually synchronize on the returned multimap when accessing
 * any of its collection views :
 * < pre > { @ code
 * Multimap < K , V > multimap = Multimaps . synchronizedMultimap (
 * HashMultimap . < K , V > create ( ) ) ;
 * Collection < V > values = multimap . get ( key ) ; / / Needn ' t be in synchronized block
 * synchronized ( multimap ) { / / Synchronizing on multimap , not values !
 * Iterator < V > i = values . iterator ( ) ; / / Must be in synchronized block
 * while ( i . hasNext ( ) ) {
 * foo ( i . next ( ) ) ;
 * } < / pre >
 * < p > Failure to follow this advice may result in non - deterministic behavior .
 * < p > Note that the generated multimap ' s { @ link Multimap # removeAll } and { @ link
 * Multimap # replaceValues } methods return collections that aren ' t synchronized .
 * < p > The returned multimap will be serializable if the specified multimap is serializable .
 * @ param multimap the multimap to be wrapped in a synchronized view
 * @ return a synchronized view of the specified multimap */
public static < K , V > Multimap < K , V > synchronizedMultimap ( Multimap < K , V > multimap ) { } }

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


signature:
public class Multimaps { /** * Returns an unmodifiable view of the specified multimap . Query operations on the returned
 * multimap " read through " to the specified multimap , and attempts to modify the returned
 * multimap , either directly or through the multimap ' s views , result in an { @ code
 * UnsupportedOperationException } .
 * < p > The returned multimap will be serializable if the specified multimap is serializable .
 * @ param delegate the multimap for which an unmodifiable view is to be returned
 * @ return an unmodifiable view of the specified multimap */
public static < K , V > Multimap < K , V > unmodifiableMultimap ( Multimap < K , V > delegate ) { } }

implementation: if ( delegate instanceof UnmodifiableMultimap || delegate instanceof ImmutableMultimap ) { return delegate ; } return new UnmodifiableMultimap < > ( delegate ) ;


signature:
public class Multimaps { /** * Simply returns its argument .
 * @ deprecated no need to use this
 * @ since 10.0 */
@ Deprecated public static < K , V > Multimap < K , V > unmodifiableMultimap ( ImmutableMultimap < K , V > delegate ) { } }

implementation: return checkNotNull ( delegate ) ;


signature:
public class Multimaps { /** * Returns a synchronized ( thread - safe ) { @ code SetMultimap } backed by the specified multimap .
 * < p > You must follow the warnings described in { @ link # synchronizedMultimap } .
 * < p > The returned multimap will be serializable if the specified multimap is serializable .
 * @ param multimap the multimap to be wrapped
 * @ return a synchronized view of the specified multimap */
public static < K , V > SetMultimap < K , V > synchronizedSetMultimap ( SetMultimap < K , V > multimap ) { } }

implementation: return Synchronized . setMultimap ( multimap , null ) ;


signature:
public class Multimaps { /** * Simply returns its argument .
 * @ deprecated no need to use this
 * @ since 10.0 */
@ Deprecated public static < K , V > SetMultimap < K , V > unmodifiableSetMultimap ( ImmutableSetMultimap < K , V > delegate ) { } }


signature:
public class Multimaps { /** * Returns a synchronized ( thread - safe ) { @ code SortedSetMultimap } backed by the specified
 * multimap .
 * < p > You must follow the warnings described in { @ link # synchronizedMultimap } .
 * < p > The returned multimap will be serializable if the specified multimap is serializable .
 * @ param multimap the multimap to be wrapped
 * @ return a synchronized view of the specified multimap */
public static < K , V > SortedSetMultimap < K , V > synchronizedSortedSetMultimap ( SortedSetMultimap < K , V > multimap ) { } }

implementation: return Synchronized . sortedSetMultimap ( multimap , null ) ;


signature:
public class Multimaps { /** * Returns an unmodifiable view of the specified { @ code SortedSetMultimap } . Query operations on
 * the returned multimap " read through " to the specified multimap , and attempts to modify the
 * returned multimap , either directly or through the multimap ' s views , result in an { @ code
 * UnsupportedOperationException } .
 * < p > The returned multimap will be serializable if the specified multimap is serializable .
 * @ param delegate the multimap for which an unmodifiable view is to be returned
 * @ return an unmodifiable view of the specified multimap */
public static < K , V > SortedSetMultimap < K , V > unmodifiableSortedSetMultimap ( SortedSetMultimap < K , V > delegate ) { } }

implementation: if ( delegate instanceof UnmodifiableSortedSetMultimap ) { return delegate ; } return new UnmodifiableSortedSetMultimap < > ( delegate ) ;


signature:
public class Multimaps { /** * Returns a synchronized ( thread - safe ) { @ code ListMultimap } backed by the specified multimap .
 * < p > You must follow the warnings described in { @ link # synchronizedMultimap } .
 * @ param multimap the multimap to be wrapped
 * @ return a synchronized view of the specified multimap */
public static < K , V > ListMultimap < K , V > synchronizedListMultimap ( ListMultimap < K , V > multimap ) { } }

implementation: return Synchronized . listMultimap ( multimap , null ) ;


signature:
public class Multimaps { /** * Returns an unmodifiable view of the specified { @ code ListMultimap } . Query operations on the
 * returned multimap " read through " to the specified multimap , and attempts to modify the returned
 * multimap , either directly or through the multimap ' s views , result in an { @ code
 * UnsupportedOperationException } .
 * < p > The returned multimap will be serializable if the specified multimap is serializable .
 * @ param delegate the multimap for which an unmodifiable view is to be returned
 * @ return an unmodifiable view of the specified multimap */
public static < K , V > ListMultimap < K , V > unmodifiableListMultimap ( ListMultimap < K , V > delegate ) { } }

implementation: if ( delegate instanceof UnmodifiableListMultimap || delegate instanceof ImmutableListMultimap ) { return delegate ; } return new UnmodifiableListMultimap < > ( delegate ) ;


signature:
public class Multimaps { /** * Simply returns its argument .
 * @ deprecated no need to use this
 * @ since 10.0 */
@ Deprecated public static < K , V > ListMultimap < K , V > unmodifiableListMultimap ( ImmutableListMultimap < K , V > delegate ) { } }


signature:
public class Multimaps { /** * Returns an unmodifiable view of the specified collection of entries . The { @ link Entry # setValue }
 * operation throws an { @ link UnsupportedOperationException } . If the specified collection is a
 * { @ code Set } , the returned collection is also a { @ code Set } .
 * @ param entries the entries for which to return an unmodifiable view
 * @ return an unmodifiable view of the entries */
private static < K , V > Collection < Entry < K , V > > unmodifiableEntries ( Collection < Entry < K , V > > entries ) { } }

implementation: if ( entries instanceof Set ) { return Maps . unmodifiableEntrySet ( ( Set < Entry < K , V > > ) entries ) ; } return new Maps . UnmodifiableEntries < > ( Collections . unmodifiableCollection ( entries ) ) ;


signature:
public class Multimaps { /** * Returns { @ link ListMultimap # asMap multimap . asMap ( ) } , with its type corrected from { @ code Map < K ,
 * Collection < V > > } to { @ code Map < K , List < V > > } .
 * @ since 15.0 */
@ Beta @ SuppressWarnings ( "unchecked" ) // safe by specification of ListMultimap . asMap ( )
public static < K , V > Map < K , List < V > > asMap ( ListMultimap < K , V > multimap ) { } }

implementation: return ( Map < K , List < V > > ) ( Map < K , ? > ) multimap . asMap ( ) ;


signature:
public class Multimaps { /** * Returns { @ link SetMultimap # asMap multimap . asMap ( ) } , with its type corrected from { @ code Map < K ,
 * Collection < V > > } to { @ code Map < K , Set < V > > } .
 * @ since 15.0 */
@ Beta @ SuppressWarnings ( "unchecked" ) // safe by specification of SetMultimap . asMap ( )
public static < K , V > Map < K , Set < V > > asMap ( SetMultimap < K , V > multimap ) { } }

implementation: return ( Map < K , Set < V > > ) ( Map < K , ? > ) multimap . asMap ( ) ;


signature:
public class Multimaps { /** * Returns { @ link SortedSetMultimap # asMap multimap . asMap ( ) } , with its type corrected from { @ code
 * Map < K , Collection < V > > } to { @ code Map < K , SortedSet < V > > } .
 * @ since 15.0 */
@ Beta @ SuppressWarnings ( "unchecked" ) // safe by specification of SortedSetMultimap . asMap ( )
public static < K , V > Map < K , SortedSet < V > > asMap ( SortedSetMultimap < K , V > multimap ) { } }

implementation: return ( Map < K , SortedSet < V > > ) ( Map < K , ? > ) multimap . asMap ( ) ;


signature:
public class Multimaps { /** * Returns { @ link Multimap # asMap multimap . asMap ( ) } . This is provided for parity with the other
 * more strongly - typed { @ code asMap ( ) } implementations .
 * @ since 15.0 */
@ Beta public static < K , V > Map < K , Collection < V > > asMap ( Multimap < K , V > multimap ) { } }

implementation: return multimap . asMap ( ) ;


signature:
public class Multimaps { /** * Returns a view of a multimap where each value is transformed by a function . All other
 * properties of the multimap , such as iteration order , are left intact . For example , the code :
 * < pre > { @ code
 * Multimap < String , Integer > multimap =
 * ImmutableSetMultimap . of ( " a " , 2 , " b " , - 3 , " b " , - 3 , " a " , 4 , " c " , 6 ) ;
 * Function < Integer , String > square = new Function < Integer , String > ( ) {
 * public String apply ( Integer in ) {
 * return Integer . toString ( in * in ) ;
 * Multimap < String , String > transformed =
 * Multimaps . transformValues ( multimap , square ) ;
 * System . out . println ( transformed ) ;
 * } < / pre >
 * . . . prints { @ code { a = [ 4 , 16 ] , b = [ 9 , 9 ] , c = [ 36 ] } } .
 * < p > Changes in the underlying multimap are reflected in this view . Conversely , this view
 * supports removal operations , and these are reflected in the underlying multimap .
 * < p > It ' s acceptable for the underlying multimap to contain null keys , and even null values
 * provided that the function is capable of accepting null input . The transformed multimap might
 * contain null values , if the function sometimes gives a null result .
 * < p > The returned multimap is not thread - safe or serializable , even if the underlying multimap
 * is . The { @ code equals } and { @ code hashCode } methods of the returned multimap are meaningless ,
 * since there is not a definition of { @ code equals } or { @ code hashCode } for general collections ,
 * and { @ code get ( ) } will return a general { @ code Collection } as opposed to a { @ code List } or a
 * { @ code Set } .
 * < p > The function is applied lazily , invoked when needed . This is necessary for the returned
 * multimap to be a view , but it means that the function will be applied many times for bulk
 * operations like { @ link Multimap # containsValue } and { @ code Multimap . toString ( ) } . For this to
 * perform well , { @ code function } should be fast . To avoid lazy evaluation when the returned
 * multimap doesn ' t need to be a view , copy the returned multimap into a new multimap of your
 * choosing .
 * @ since 7.0 */
public static < K , V1 , V2 > Multimap < K , V2 > transformValues ( Multimap < K , V1 > fromMultimap , final Function < ? super V1 , V2 > function ) { } }

implementation: checkNotNull ( function ) ; EntryTransformer < K , V1 , V2 > transformer = Maps . asEntryTransformer ( function ) ; return transformEntries ( fromMultimap , transformer ) ;


signature:
public class Multimaps { /** * Creates an index { @ code ImmutableListMultimap } that contains the results of applying a
 * specified function to each item in an { @ code Iterable } of values . Each value will be stored as
 * a value in the resulting multimap , yielding a multimap with the same size as the input
 * iterable . The key used to store that value in the multimap will be the result of calling the
 * function on that value . The resulting multimap is created as an immutable snapshot . In the
 * returned multimap , keys appear in the order they are first encountered , and the values
 * corresponding to each key appear in the same order as they are encountered .
 * < p > For example ,
 * < pre > { @ code
 * List < String > badGuys =
 * Arrays . asList ( " Inky " , " Blinky " , " Pinky " , " Pinky " , " Clyde " ) ;
 * Function < String , Integer > stringLengthFunction = . . . ;
 * Multimap < Integer , String > index =
 * Multimaps . index ( badGuys , stringLengthFunction ) ;
 * System . out . println ( index ) ;
 * } < / pre >
 * < p > prints
 * < pre > { @ code
 * { 4 = [ Inky ] , 6 = [ Blinky ] , 5 = [ Pinky , Pinky , Clyde ] }
 * } < / pre >
 * < p > The returned multimap is serializable if its keys and values are all serializable .
 * @ param values the values to use when constructing the { @ code ImmutableListMultimap }
 * @ param keyFunction the function used to produce the key for each value
 * @ return { @ code ImmutableListMultimap } mapping the result of evaluating the function { @ code
 * keyFunction } on each value in the input collection to that value
 * @ throws NullPointerException if any element of { @ code values } is { @ code null } , or if { @ code
 * keyFunction } produces { @ code null } for any key */
public static < K , V > ImmutableListMultimap < K , V > index ( Iterable < V > values , Function < ? super V , K > keyFunction ) { } }

implementation: return index ( values . iterator ( ) , keyFunction ) ;