@CanIgnoreReturnValue
  public static <T> T verifyNotNull(
      @Nullable T reference,
      @Nullable String errorMessageTemplate,
      @Nullable Object @Nullable ... errorMessageArgs) {
    verify(reference != null, errorMessageTemplate, errorMessageArgs);
    return reference;
  }

@ CanIgnoreReturnValue public static < T > T verifyNotNull ( @ Nullable T reference , @ Nullable String errorMessageTemplate , @ Nullable Object @ Nullable . . . errorMessageArgs ) { verify ( reference != null , errorMessageTemplate , errorMessageArgs ) ; return reference ; }

Ensures that {@code reference} is non-null, throwing a {@code VerifyException} with a custom
message otherwise.

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

Ensures that { @code reference } is non - null throwing a { @code VerifyException } with a custom message otherwise .


public static <E> ArrayDeque<E> newArrayDeque(Iterable<? extends E> elements) {
    if (elements instanceof Collection) {
      return new ArrayDeque<E>(Collections2.cast(elements));
    }
    ArrayDeque<E> deque = new ArrayDeque<E>();
    Iterables.addAll(deque, elements);
    return deque;
  }

public static < E > ArrayDeque < E > newArrayDeque ( Iterable < ? extends E > elements ) { if ( elements instanceof Collection ) { return new ArrayDeque < E > ( Collections2 . cast ( elements ) ) ; } ArrayDeque < E > deque = new ArrayDeque < E > ( ) ; Iterables . addAll ( deque , elements ) ; return deque ; }

Creates an {@code ArrayDeque} containing the elements of the specified iterable, in the order
they are returned by the iterable's iterator.

@since 12.0

Creates an { @code ArrayDeque } containing the elements of the specified iterable in the order they are returned by the iterable s iterator .


@GwtIncompatible // ConcurrentLinkedQueue
  public static <E> ConcurrentLinkedQueue<E> newConcurrentLinkedQueue(
      Iterable<? extends E> elements) {
    if (elements instanceof Collection) {
      return new ConcurrentLinkedQueue<E>(Collections2.cast(elements));
    }
    ConcurrentLinkedQueue<E> queue = new ConcurrentLinkedQueue<E>();
    Iterables.addAll(queue, elements);
    return queue;
  }

@
GwtIncompatible
// ConcurrentLinkedQueue
public
static
<
E
>
ConcurrentLinkedQueue
<
E
>
newConcurrentLinkedQueue
(
Iterable
<
extends
E
>
elements
)
{
if
(
elements
instanceof
Collection
)
{
return
new
ConcurrentLinkedQueue
<
E
>
(
Collections2
.
cast
(
elements
)
)
;
}
ConcurrentLinkedQueue
<
E
>
queue
=
new
ConcurrentLinkedQueue
<
E
>
(
)
;
Iterables
.
addAll
(
queue
,
elements
)
;
return
queue
;
}

Creates a {@code ConcurrentLinkedQueue} containing the elements of the specified iterable, in
the order they are returned by the iterable's iterator.


@GwtIncompatible // LinkedBlockingQueue
  public static <E> LinkedBlockingQueue<E> newLinkedBlockingQueue(Iterable<? extends E> elements) {
    if (elements instanceof Collection) {
      return new LinkedBlockingQueue<E>(Collections2.cast(elements));
    }
    LinkedBlockingQueue<E> queue = new LinkedBlockingQueue<E>();
    Iterables.addAll(queue, elements);
    return queue;
  }

@
GwtIncompatible
// LinkedBlockingQueue
public
static
<
E
>
LinkedBlockingQueue
<
E
>
newLinkedBlockingQueue
(
Iterable
<
extends
E
>
elements
)
{
if
(
elements
instanceof
Collection
)
{
return
new
LinkedBlockingQueue
<
E
>
(
Collections2
.
cast
(
elements
)
)
;
}
LinkedBlockingQueue
<
E
>
queue
=
new
LinkedBlockingQueue
<
E
>
(
)
;
Iterables
.
addAll
(
queue
,
elements
)
;
return
queue
;
}

Creates a {@code LinkedBlockingQueue} with a capacity of {@link Integer#MAX_VALUE}, containing
the elements of the specified iterable, in the order they are returned by the iterable's
iterator.

@param elements the elements that the queue should contain, in order
@return a new {@code LinkedBlockingQueue} containing those elements

Creates a { @code LinkedBlockingQueue } with a capacity of { @link Integer#MAX_VALUE } containing the elements of the specified iterable in the order they are returned by the iterable s iterator .


public static <E extends Comparable> PriorityQueue<E> newPriorityQueue(
      Iterable<? extends E> elements) {
    if (elements instanceof Collection) {
      return new PriorityQueue<E>(Collections2.cast(elements));
    }
    PriorityQueue<E> queue = new PriorityQueue<E>();
    Iterables.addAll(queue, elements);
    return queue;
  }

public static < E extends Comparable > PriorityQueue < E > newPriorityQueue ( Iterable < ? extends E > elements ) { if ( elements instanceof Collection ) { return new PriorityQueue < E > ( Collections2 . cast ( elements ) ) ; } PriorityQueue < E > queue = new PriorityQueue < E > ( ) ; Iterables . addAll ( queue , elements ) ; return queue ; }

Creates a {@code PriorityQueue} containing the given elements.

Note: If the specified iterable is a {@code SortedSet} or a {@code PriorityQueue},
this priority queue will be ordered according to the same ordering.

@since 11.0 (requires that {@code E} be {@code Comparable} since 15.0).

Creates a { @code PriorityQueue } containing the given elements .


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

Drains the queue as {@linkplain #drain(BlockingQueue, Collection, int, long, TimeUnit)}, but
with a different behavior in case it is interrupted while waiting. In that case, the operation
will continue as usual, and in the end the thread's interruption status will be set (no {@code
InterruptedException} is thrown).

@param q the blocking queue to be drained
@param buffer where to add the transferred elements
@param numElements the number of elements to be waited for
@param timeout how long to wait before giving up, in units of {@code unit}
@param unit a {@code TimeUnit} determining how to interpret the timeout parameter
@return the number of elements transferred

Drains the queue as { @linkplain #drain ( BlockingQueue Collection int long TimeUnit ) } but with a different behavior in case it is interrupted while waiting . In that case the operation will continue as usual and in the end the thread s interruption status will be set ( no { @code InterruptedException } is thrown ) .


public static <E> Queue<E> synchronizedQueue(Queue<E> queue) {
    return Synchronized.queue(queue, null);
  }

public static < E > Queue < E > synchronizedQueue ( Queue < E > queue ) { return Synchronized . queue ( queue , null ) ; }

Returns a synchronized (thread-safe) queue backed by the specified queue. In order to guarantee
serial access, it is critical that all access to the backing queue is accomplished
through the returned queue.

It is imperative that the user manually synchronize on the returned queue when accessing the
queue's iterator:

{@code
Queue<E> queue = Queues.synchronizedQueue(MinMaxPriorityQueue.<E>create());
...
queue.add(element);  // Needn't be in synchronized block
...
synchronized (queue) {  // Must synchronize on queue!
Iterator<E> i = queue.iterator(); // Must be in synchronized block
while (i.hasNext()) {
foo(i.next());
}
}
}

Failure to follow this advice may result in non-deterministic behavior.

The returned queue will be serializable if the specified queue is serializable.

@param queue the queue to be wrapped in a synchronized view
@return a synchronized view of the specified queue
@since 14.0

Returns a synchronized ( thread - safe ) queue backed by the specified queue . In order to guarantee serial access it is critical that <b > all< / b > access to the backing queue is accomplished through the returned queue .


public static <E> Deque<E> synchronizedDeque(Deque<E> deque) {
    return Synchronized.deque(deque, null);
  }

public static < E > Deque < E > synchronizedDeque ( Deque < E > deque ) { return Synchronized . deque ( deque , null ) ; }

Returns a synchronized (thread-safe) deque backed by the specified deque. In order to guarantee
serial access, it is critical that all access to the backing deque is accomplished
through the returned deque.

It is imperative that the user manually synchronize on the returned deque when accessing any
of the deque's iterators:

{@code
Deque<E> deque = Queues.synchronizedDeque(Queues.<E>newArrayDeque());
...
deque.add(element);  // Needn't be in synchronized block
...
synchronized (deque) {  // Must synchronize on deque!
Iterator<E> i = deque.iterator(); // Must be in synchronized block
while (i.hasNext()) {
foo(i.next());
}
}
}

Failure to follow this advice may result in non-deterministic behavior.

The returned deque will be serializable if the specified deque is serializable.

@param deque the deque to be wrapped in a synchronized view
@return a synchronized view of the specified deque
@since 15.0

Returns a synchronized ( thread - safe ) deque backed by the specified deque . In order to guarantee serial access it is critical that <b > all< / b > access to the backing deque is accomplished through the returned deque .


private boolean removeMapping(Object rowKey, Object columnKey, Object value) {
    if (containsMapping(rowKey, columnKey, value)) {
      remove(rowKey, columnKey);
      return true;
    }
    return false;
  }

private boolean removeMapping ( Object rowKey , Object columnKey , Object value ) { if ( containsMapping ( rowKey , columnKey , value ) ) { remove ( rowKey , columnKey ) ; return true ; } return false ; }

Remove a row key / column key / value mapping, if present.

Remove a row key / column key / value mapping if present .


@Override
  public Set<C> columnKeySet() {
    Set<C> result = columnKeySet;
    return (result == null) ? columnKeySet = new ColumnKeySet() : result;
  }

@ Override public Set < C > columnKeySet ( ) { Set < C > result = columnKeySet ; return ( result == null ) ? columnKeySet = new ColumnKeySet ( ) : result ; }

{@inheritDoc}

The returned set has an iterator that does not support {@code remove()}.

The set's iterator traverses the columns of the first row, the columns of the second row,
etc., skipping any columns that have appeared previously.


public static CacheBuilderSpec parse(String cacheBuilderSpecification) {
    CacheBuilderSpec spec = new CacheBuilderSpec(cacheBuilderSpecification);
    if (!cacheBuilderSpecification.isEmpty()) {
      for (String keyValuePair : KEYS_SPLITTER.split(cacheBuilderSpecification)) {
        List<String> keyAndValue = ImmutableList.copyOf(KEY_VALUE_SPLITTER.split(keyValuePair));
        checkArgument(!keyAndValue.isEmpty(), "blank key-value pair");
        checkArgument(
            keyAndValue.size() <= 2,
            "key-value pair %s with more than one equals sign",
            keyValuePair);

        // Find the ValueParser for the current key.
        String key = keyAndValue.get(0);
        ValueParser valueParser = VALUE_PARSERS.get(key);
        checkArgument(valueParser != null, "unknown key %s", key);

        String value = keyAndValue.size() == 1 ? null : keyAndValue.get(1);
        valueParser.parse(spec, key, value);
      }
    }

    return spec;
  }

Creates a CacheBuilderSpec from a string.

@param cacheBuilderSpecification the string form

Creates a CacheBuilderSpec from a string .


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

    return builder;
  }

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

Returns a CacheBuilder configured according to this instance's specification.

Returns a CacheBuilder configured according to this instance s specification .


@NullableDecl
  private static Long durationInNanos(long duration, @NullableDecl TimeUnit unit) {
    return (unit == null) ? null : unit.toNanos(duration);
  }

@ NullableDecl private static Long durationInNanos ( long duration , @ NullableDecl TimeUnit unit ) { return ( unit == null ) ? null : unit . toNanos ( duration ) ; }

Converts an expiration duration/unit pair into a single Long for hashing and equality. Uses
nanos to match CacheBuilder implementation.

Converts an expiration duration / unit pair into a single Long for hashing and equality . Uses nanos to match CacheBuilder implementation .


public static <K extends Enum<K>, V extends Enum<V>> EnumBiMap<K, V> create(
      Class<K> keyType, Class<V> valueType) {
    return new EnumBiMap<>(keyType, valueType);
  }

public static < K extends Enum < K > , V extends Enum < V > > EnumBiMap < K , V > create ( Class < K > keyType , Class < V > valueType ) { return new EnumBiMap <> ( keyType , valueType ) ; }

Returns a new, empty {@code EnumBiMap} using the specified key and value types.

@param keyType the key type
@param valueType the value type

Returns a new empty { @code EnumBiMap } using the specified key and value types .


@Beta
  public static <T> boolean isInOrder(Iterable<? extends T> iterable, Comparator<T> comparator) {
    checkNotNull(comparator);
    Iterator<? extends T> it = iterable.iterator();
    if (it.hasNext()) {
      T prev = it.next();
      while (it.hasNext()) {
        T next = it.next();
        if (comparator.compare(prev, next) > 0) {
          return false;
        }
        prev = next;
      }
    }
    return true;
  }

@ Beta public static < T > boolean isInOrder ( Iterable < ? extends T > iterable , Comparator < T > comparator ) { checkNotNull ( comparator ) ; Iterator < ? extends T > it = iterable . iterator ( ) ; if ( it . hasNext ( ) ) { T prev = it . next ( ) ; while ( it . hasNext ( ) ) { T next = it . next ( ) ; if ( comparator . compare ( prev , next ) > 0 ) { return false ; } prev = next ; } } return true ; }

Returns {@code true} if each element in {@code iterable} after the first is greater than or
equal to the element that preceded it, according to the specified comparator. Note that this is
always true when the iterable has fewer than two elements.


public static <T> Collector<T, ?, List<T>> least(int k, Comparator<? super T> comparator) {
    checkNonnegative(k, "k");
    checkNotNull(comparator);
    return Collector.of(
        () -> TopKSelector.<T>least(k, comparator),
        TopKSelector::offer,
        TopKSelector::combine,
        TopKSelector::topK,
        Collector.Characteristics.UNORDERED);
  }

public static < T > Collector < T , ? , List < T > > least ( int k , Comparator < ? super T > comparator ) { checkNonnegative ( k , "k" ) ; checkNotNull ( comparator ) ; return Collector . of ( ( ) -> TopKSelector . < T > least ( k , comparator ) , TopKSelector :: offer , TopKSelector :: combine , TopKSelector :: topK , Collector . Characteristics . UNORDERED ) ; }

Returns a {@code Collector} that returns the {@code k} smallest (relative to the specified
{@code Comparator}) input elements, in ascending order, as an unmodifiable {@code List}. Ties
are broken arbitrarily.

For example:

{@code
Stream.of("foo", "quux", "banana", "elephant")
.collect(least(2, comparingInt(String::length)))
// returns {"foo", "quux"}
}

This {@code Collector} uses O(k) memory and takes expected time O(n) (worst-case O(n log
k)), as opposed to e.g. {@code Stream.sorted(comparator).limit(k)}, which currently takes O(n
log n) time and O(n) space.

@throws IllegalArgumentException if {@code k < 0}
@since 22.0

Returns a { @code Collector } that returns the { @code k } smallest ( relative to the specified { @code Comparator } ) input elements in ascending order as an unmodifiable { @code List } . Ties are broken arbitrarily .


@Beta
  public static <T> Comparator<Optional<T>> emptiesFirst(Comparator<? super T> valueComparator) {
    checkNotNull(valueComparator);
    return Comparator.comparing(o -> o.orElse(null), Comparator.nullsFirst(valueComparator));
  }

@ Beta public static < T > Comparator < Optional < T > > emptiesFirst ( Comparator < ? super T > valueComparator ) { checkNotNull ( valueComparator ) ; return Comparator . comparing ( o -> o . orElse ( null ) , Comparator . nullsFirst ( valueComparator ) ) ; }

Returns a comparator of {@link Optional} values which treats {@link Optional#empty} as less
than all other values, and orders the rest using {@code valueComparator} on the contained
value.

@since 22.0

Returns a comparator of { @link Optional } values which treats { @link Optional#empty } as less than all other values and orders the rest using { @code valueComparator } on the contained value .


@Beta
  public static <T> Comparator<Optional<T>> emptiesLast(Comparator<? super T> valueComparator) {
    checkNotNull(valueComparator);
    return Comparator.comparing(o -> o.orElse(null), Comparator.nullsLast(valueComparator));
  }

@ Beta public static < T > Comparator < Optional < T > > emptiesLast ( Comparator < ? super T > valueComparator ) { checkNotNull ( valueComparator ) ; return Comparator . comparing ( o -> o . orElse ( null ) , Comparator . nullsLast ( valueComparator ) ) ; }

Returns a comparator of {@link Optional} values which treats {@link Optional#empty} as greater
than all other values, and orders the rest using {@code valueComparator} on the contained
value.

@since 22.0

Returns a comparator of { @link Optional } values which treats { @link Optional#empty } as greater than all other values and orders the rest using { @code valueComparator } on the contained value .


@Beta
  @MustBeClosed
  public Stream<String> lines() throws IOException {
    BufferedReader reader = openBufferedStream();
    return reader
        .lines()
        .onClose(
            () -> {
              try {
                reader.close();
              } catch (IOException e) {
                throw new UncheckedIOException(e);
              }
            });
  }

@ Beta @ MustBeClosed public Stream < String > lines ( ) throws IOException { BufferedReader reader = openBufferedStream ( ) ; return reader . lines ( ) . onClose ( ( ) -> { try { reader . close ( ) ; } catch ( IOException e ) { throw new UncheckedIOException ( e ) ; } } ) ; }

Opens a new {@link Stream} for reading text one line at a time from this source. This method
returns a new, independent stream each time it is called.

The returned stream is lazy and only reads from the source in the terminal operation. If an
I/O error occurs while the stream is reading from the source or when the stream is closed, an
{@link UncheckedIOException} is thrown.

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

The caller is responsible for ensuring that the returned stream is closed. For example:

{@code
try (Stream<String> lines = source.lines()) {
lines.map(...)
.filter(...)
.forEach(...);
}
}

@throws IOException if an I/O error occurs while opening the stream
@since 22.0

Opens a new { @link Stream } for reading text one line at a time from this source . This method returns a new independent stream each time it is called .


@Beta
  public void forEachLine(Consumer<? super String> action) throws IOException {
    try (Stream<String> lines = lines()) {
      // The lines should be ordered regardless in most cases, but use forEachOrdered to be sure
      lines.forEachOrdered(action);
    } catch (UncheckedIOException e) {
      throw e.getCause();
    }
  }

Reads all lines of text from this source, running the given {@code action} for each line as it
is read.

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

@throws IOException if an I/O error occurs while reading from this source or if {@code action}
throws an {@code UncheckedIOException}
@since 22.0

Reads all lines of text from this source running the given { @code action } for each line as it is read .


public static <T> Optional<T> fromNullable(@Nullable T nullableReference) {
    return (nullableReference == null) ? Optional.<T>absent() : new Present<T>(nullableReference);
  }

public static < T > Optional < T > fromNullable ( @ Nullable T nullableReference ) { return ( nullableReference == null ) ? Optional . < T > absent ( ) : new Present < T > ( nullableReference ) ; }

If {@code nullableReference} is non-null, returns an {@code Optional} instance containing that
reference; otherwise returns {@link Optional#absent}.

Comparison to {@code java.util.Optional}: this method is equivalent to Java 8's
{@code Optional.ofNullable}.

If { @code nullableReference } is non - null returns an { @code Optional } instance containing that reference ; otherwise returns { @link Optional#absent } .


public static <T> @Nullable Optional<T> fromJavaUtil(
      java.util.@Nullable Optional<T> javaUtilOptional) {
    return (javaUtilOptional == null) ? null : fromNullable(javaUtilOptional.orElse(null));
  }

public static < T > @ Nullable Optional < T > fromJavaUtil ( java . util . @ Nullable Optional < T > javaUtilOptional ) { return ( javaUtilOptional == null ) ? null : fromNullable ( javaUtilOptional . orElse ( null ) ) ; }

Returns the equivalent {@code com.google.common.base.Optional} value to the given {@code
java.util.Optional}, or {@code null} if the argument is null.

@since 21.0

Returns the equivalent { @code com . google . common . base . Optional } value to the given { @code java . util . Optional } or { @code null } if the argument is null .


public static <T> java.util.@Nullable Optional<T> toJavaUtil(
      @Nullable Optional<T> googleOptional) {
    return googleOptional == null ? null : googleOptional.toJavaUtil();
  }

public static < T > java . util . @ Nullable Optional < T > toJavaUtil ( @ Nullable Optional < T > googleOptional ) { return googleOptional == null ? null : googleOptional . toJavaUtil ( ) ; }

Returns the equivalent {@code java.util.Optional} value to the given {@code
com.google.common.base.Optional}, or {@code null} if the argument is null.

If {@code googleOptional} is known to be non-null, use {@code googleOptional.toJavaUtil()}
instead.

Unfortunately, the method reference {@code Optional::toJavaUtil} will not work, because it
could refer to either the static or instance version of this method. Write out the lambda
expression {@code o -> Optional.toJavaUtil(o)} instead.

@since 21.0

Returns the equivalent { @code java . util . Optional } value to the given { @code com . google . common . base . Optional } or { @code null } if the argument is null .


public java.util.Optional<T> toJavaUtil() {
    return java.util.Optional.ofNullable(orNull());
  }

public java . util . Optional < T > toJavaUtil ( ) { return java . util . Optional . ofNullable ( orNull ( ) ) ; }

Returns the equivalent {@code java.util.Optional} value to this optional.

<p>Unfortunately, the method reference {@code Optional::toJavaUtil} will not work, because it
could refer to either the static or instance version of this method. Write out the lambda
expression {@code o -> o.toJavaUtil()} instead.

@since 21.0

Returns the equivalent { @code java . util . Optional } value to this optional .


@Beta
  public static <T> Iterable<T> presentInstances(
      final Iterable<? extends Optional<? extends T>> optionals) {
    checkNotNull(optionals);
    return new Iterable<T>() {
      @Override
      public Iterator<T> iterator() {
        return new AbstractIterator<T>() {
          private final Iterator<? extends Optional<? extends T>> iterator =
              checkNotNull(optionals.iterator());

          @Override
          protected T computeNext() {
            while (iterator.hasNext()) {
              Optional<? extends T> optional = iterator.next();
              if (optional.isPresent()) {
                return optional.get();
              }
            }
            return endOfData();
          }
        };
      }
    };
  }

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

Returns the value of each present instance from the supplied {@code optionals}, in order,
skipping over occurrences of {@link Optional#absent}. Iterators are unmodifiable and are
evaluated lazily.

Comparison to {@code java.util.Optional}: this method has no equivalent in Java 8's
{@code Optional} class; use {@code
optionals.stream().filter(Optional::isPresent).map(Optional::get)} instead.

@since 11.0 (generics widened in 13.0)

Returns the value of each present instance from the supplied { @code optionals } in order skipping over occurrences of { @link Optional#absent } . Iterators are unmodifiable and are evaluated lazily .


@SuppressWarnings("unchecked")
  public static <K, V> ImmutableSetMultimap<K, V> of() {
    return (ImmutableSetMultimap<K, V>) EmptyImmutableSetMultimap.INSTANCE;
  }

@ SuppressWarnings ( "unchecked" ) public static < K , V > ImmutableSetMultimap < K , V > of ( ) { return ( ImmutableSetMultimap < K , V > ) EmptyImmutableSetMultimap . INSTANCE ; }

Casting is safe because the multimap will never hold any elements.

Casting is safe because the multimap will never hold any elements .


public static <K, V> ImmutableSetMultimap<K, V> copyOf(
      Multimap<? extends K, ? extends V> multimap) {
    return copyOf(multimap, null);
  }

public static < K , V > ImmutableSetMultimap < K , V > copyOf ( Multimap < ? extends K , ? extends V > multimap ) { return copyOf ( multimap , null ) ; }

Returns an immutable set multimap containing the same mappings as {@code multimap}. The
generated multimap's key and value orderings correspond to the iteration ordering of the {@code
multimap.asMap()} view. Repeated occurrences of an entry in the multimap after the first are
ignored.

<p>Despite the method name, this method attempts to avoid actually copying the data when it is
safe to do so. The exact circumstances under which a copy will or will not be performed are
undocumented and subject to change.

@throws NullPointerException if any key or value in {@code multimap} is null

Returns an immutable set multimap containing the same mappings as { @code multimap } . The generated multimap s key and value orderings correspond to the iteration ordering of the { @code multimap . asMap () } view . Repeated occurrences of an entry in the multimap after the first are ignored .


@Override
  public ImmutableSetMultimap<V, K> inverse() {
    ImmutableSetMultimap<V, K> result = inverse;
    return (result == null) ? (inverse = invert()) : result;
  }

@ Override public ImmutableSetMultimap < V , K > inverse ( ) { ImmutableSetMultimap < V , K > result = inverse ; return ( result == null ) ? ( inverse = invert ( ) ) : result ; }

{@inheritDoc}

<p>Because an inverse of a set multimap cannot contain multiple pairs with the same key and
value, this method returns an {@code ImmutableSetMultimap} rather than the {@code
ImmutableMultimap} specified in the {@code ImmutableMultimap} class.


@CanIgnoreReturnValue
  public <A extends Appendable> A appendTo(A appendable, Iterator<?> parts) throws IOException {
    checkNotNull(appendable);
    if (parts.hasNext()) {
      appendable.append(toString(parts.next()));
      while (parts.hasNext()) {
        appendable.append(separator);
        appendable.append(toString(parts.next()));
      }
    }
    return appendable;
  }

@ CanIgnoreReturnValue public < A extends Appendable > A appendTo ( A appendable , Iterator < ? > parts ) throws IOException { checkNotNull ( appendable ) ; if ( parts . hasNext ( ) ) { appendable . append ( toString ( parts . next ( ) ) ) ; while ( parts . hasNext ( ) ) { appendable . append ( separator ) ; appendable . append ( toString ( parts . next ( ) ) ) ; } } return appendable ; }

Appends the string representation of each of {@code parts}, using the previously configured
separator between each, to {@code appendable}.

@since 11.0

Appends the string representation of each of { @code parts } using the previously configured separator between each to { @code appendable } .


@CanIgnoreReturnValue
  public final StringBuilder appendTo(StringBuilder builder, Iterable<?> parts) {
    return appendTo(builder, parts.iterator());
  }

@ CanIgnoreReturnValue public final StringBuilder appendTo ( StringBuilder builder , Iterable < ? > parts ) { return appendTo ( builder , parts . iterator ( ) ) ; }

Appends the string representation of each of {@code parts}, using the previously configured
separator between each, to {@code builder}. Identical to {@link #appendTo(Appendable,
Iterable)}, except that it does not throw {@link IOException}.


@CanIgnoreReturnValue
  public final StringBuilder appendTo(StringBuilder builder, Object[] parts) {
    return appendTo(builder, Arrays.asList(parts));
  }

@ CanIgnoreReturnValue public final StringBuilder appendTo ( StringBuilder builder , Object [ ] parts ) { return appendTo ( builder , Arrays . asList ( parts ) ) ; }


@CanIgnoreReturnValue
  public final StringBuilder appendTo(
      StringBuilder builder, @Nullable Object first, @Nullable Object second, Object... rest) {
    return appendTo(builder, iterable(first, second, rest));
  }

@ CanIgnoreReturnValue public final StringBuilder appendTo ( StringBuilder builder , @ Nullable Object first , @ Nullable Object second , Object ... rest ) { return appendTo ( builder , iterable ( first , second , rest ) ) ; }

Appends to {@code builder} the string representation of each of the remaining arguments.
Identical to {@link #appendTo(Appendable, Object, Object, Object...)}, except that it does not
throw {@link IOException}.


public final String join(@Nullable Object first, @Nullable Object second, Object... rest) {
    return join(iterable(first, second, rest));
  }

public final String join ( @ Nullable Object first , @ Nullable Object second , Object ... rest ) { return join ( iterable ( first , second , rest ) ) ; }

Returns a string containing the string representation of each argument, using the previously
configured separator between each.

Returns a string containing the string representation of each argument using the previously configured separator between each .


public Joiner skipNulls() {
    return new Joiner(this) {
      @Override
      public <A extends Appendable> A appendTo(A appendable, Iterator<?> parts) throws IOException {
        checkNotNull(appendable, "appendable");
        checkNotNull(parts, "parts");
        while (parts.hasNext()) {
          Object part = parts.next();
          if (part != null) {
            appendable.append(Joiner.this.toString(part));
            break;
          }
        }
        while (parts.hasNext()) {
          Object part = parts.next();
          if (part != null) {
            appendable.append(separator);
            appendable.append(Joiner.this.toString(part));
          }
        }
        return appendable;
      }

      @Override
      public Joiner useForNull(String nullText) {
        throw new UnsupportedOperationException("already specified skipNulls");
      }

      @Override
      public MapJoiner withKeyValueSeparator(String kvs) {
        throw new UnsupportedOperationException("can't use .skipNulls() with maps");
      }
    };
  }

public
Joiner
skipNulls
(
)
{
return
new
Joiner
(
this
)
{
@
Override
public
<
A
extends
Appendable
>
A
appendTo
(
A
appendable
,
Iterator
<
>
parts
)
throws
IOException
{
checkNotNull
(
appendable
,
"appendable"
)
;
checkNotNull
(
parts
,
"parts"
)
;
while
(
parts
.
hasNext
(
)
)
{
Object
part
=
parts
.
next
(
)
;
if
(
part
!=
)
{
appendable
.
append
(
Joiner
.
this
.
toString
(
part
)
)
;
break
;
}
}
while
(
parts
.
hasNext
(
)
)
{
Object
part
=
parts
.
next
(
)
;
if
(
part
!=
)
{
appendable
.
append
(
separator
)
;
appendable
.
append
(
Joiner
.
this
.
toString
(
part
)
)
;
}
}
return
appendable
;
}
@
Override
public
Joiner
useForNull
(
String
nullText
)
{
throw
new
UnsupportedOperationException
(
"already specified skipNulls"
)
;
}
@
Override
public
MapJoiner
withKeyValueSeparator
(
String
kvs
)
{
throw
new
UnsupportedOperationException
(
"can't use .skipNulls() with maps"
)
;
}
}
;
}

Returns a joiner with the same behavior as this joiner, except automatically skipping over any
provided null elements.

Returns a joiner with the same behavior as this joiner except automatically skipping over any provided null elements .


public static ImmutableIntArray of(int e0, int e1, int e2, int e3) {
    return new ImmutableIntArray(new int[] {e0, e1, e2, e3});
  }

public static ImmutableIntArray of ( int e0 , int e1 , int e2 , int e3 ) { return new ImmutableIntArray ( new int [ ] { e0 , e1 , e2 , e3 } ) ; }

Returns an immutable array containing the given values, in order.

Returns an immutable array containing the given values in order .


public static ImmutableIntArray of(int first, int... rest) {
    checkArgument(
        rest.length <= Integer.MAX_VALUE - 1, "the total number of elements must fit in an int");
    int[] array = new int[rest.length + 1];
    array[0] = first;
    System.arraycopy(rest, 0, array, 1, rest.length);
    return new ImmutableIntArray(array);
  }

okay since we have to copy the just-created array anyway.

okay since we have to copy the just - created array anyway .


public static ImmutableIntArray copyOf(int[] values) {
    return values.length == 0 ? EMPTY : new ImmutableIntArray(Arrays.copyOf(values, values.length));
  }

public static ImmutableIntArray copyOf ( int [ ] values ) { return values . length == 0 ? EMPTY : new ImmutableIntArray ( Arrays . copyOf ( values , values . length ) ) ; }


public static ImmutableIntArray copyOf(Collection<Integer> values) {
    return values.isEmpty() ? EMPTY : new ImmutableIntArray(Ints.toArray(values));
  }

public static ImmutableIntArray copyOf ( Collection < Integer > values ) { return values . isEmpty ( ) ? EMPTY : new ImmutableIntArray ( Ints . toArray ( values ) ) ; }


public static ImmutableIntArray copyOf(Iterable<Integer> values) {
    if (values instanceof Collection) {
      return copyOf((Collection<Integer>) values);
    }
    return builder().addAll(values).build();
  }

public static ImmutableIntArray copyOf ( Iterable < Integer > values ) { if ( values instanceof Collection ) { return copyOf ( ( Collection < Integer > ) values ) ; } return builder ( ) . addAll ( values ) . build ( ) ; }

Returns an immutable array containing the given values, in order.

Performance note: this method delegates to {@link #copyOf(Collection)} if {@code
values} is a {@link Collection}. Otherwise it creates a {@link #builder} and uses {@link
Builder#addAll(Iterable)}, with all the performance implications associated with that.


public static ImmutableIntArray copyOf(IntStream stream) {
    // Note this uses very different growth behavior from copyOf(Iterable) and the builder.
    int[] array = stream.toArray();
    return (array.length == 0) ? EMPTY : new ImmutableIntArray(array);
  }

Returns an immutable array containing all the values from {@code stream}, in order.


public int indexOf(int target) {
    for (int i = start; i < end; i++) {
      if (array[i] == target) {
        return i - start;
      }
    }
    return -1;
  }

public int indexOf ( int target ) { for ( int i = start ; i < end ; i ++ ) { if ( array [ i ] == target ) { return i - start ; } } return - 1 ; }

Returns the smallest index for which {@link #get} returns {@code target}, or {@code -1} if no
such index exists. Equivalent to {@code asList().indexOf(target)}.


public ImmutableIntArray subArray(int startIndex, int endIndex) {
    Preconditions.checkPositionIndexes(startIndex, endIndex, length());
    return startIndex == endIndex
        ? EMPTY
        : new ImmutableIntArray(array, start + startIndex, start + endIndex);
  }

public ImmutableIntArray subArray ( int startIndex , int endIndex ) { Preconditions . checkPositionIndexes ( startIndex , endIndex , length ( ) ) ; return startIndex == endIndex ? EMPTY : new ImmutableIntArray ( array , start + startIndex , start + endIndex ) ; }

Returns a new immutable array containing the values in the specified range.

Performance note: The returned array has the same full memory footprint as this one
does (no actual copying is performed). To reduce memory usage, use {@code subArray(start,
end).trimmed()}.

Returns a new immutable array containing the values in the specified range .


@GwtIncompatible // #roundIntermediate
  public static int roundToInt(double x, RoundingMode mode) {
    double z = roundIntermediate(x, mode);
    checkInRangeForRoundingInputs(
        z > MIN_INT_AS_DOUBLE - 1.0 & z < MAX_INT_AS_DOUBLE + 1.0, x, mode);
    return (int) z;
  }

@
GwtIncompatible
// #roundIntermediate
public
static
int
roundToInt
(
double
x
,
RoundingMode
mode
)
{
double
z
=
roundIntermediate
(
x
,
mode
)
;
checkInRangeForRoundingInputs
(
z
>
MIN_INT_AS_DOUBLE
1.0
&
z
<
MAX_INT_AS_DOUBLE
+
1.0
,
x
,
mode
)
;
return
(
int
)
z
;
}

Returns the {@code int} value that is equal to {@code x} rounded with the specified rounding
mode, if possible.

@throws ArithmeticException if
<ul>
<li>{@code x} is infinite or NaN
<li>{@code x}, after being rounded to a mathematical integer using the specified rounding
mode, is either less than {@code Integer.MIN_VALUE} or greater than {@code
Integer.MAX_VALUE}
<li>{@code x} is not a mathematical integer and {@code mode} is {@link
RoundingMode#UNNECESSARY}
</ul>

Returns the { @code int } value that is equal to { @code x } rounded with the specified rounding mode if possible .


@GwtIncompatible // #roundIntermediate
  public static long roundToLong(double x, RoundingMode mode) {
    double z = roundIntermediate(x, mode);
    checkInRangeForRoundingInputs(
        MIN_LONG_AS_DOUBLE - z < 1.0 & z < MAX_LONG_AS_DOUBLE_PLUS_ONE, x, mode);
    return (long) z;
  }

@
GwtIncompatible
// #roundIntermediate
public
static
long
roundToLong
(
double
x
,
RoundingMode
mode
)
{
double
z
=
roundIntermediate
(
x
,
mode
)
;
checkInRangeForRoundingInputs
(
MIN_LONG_AS_DOUBLE
z
<
1.0
&
z
<
MAX_LONG_AS_DOUBLE_PLUS_ONE
,
x
,
mode
)
;
return
(
long
)
z
;
}

Returns the {@code long} value that is equal to {@code x} rounded with the specified rounding
mode, if possible.

@throws ArithmeticException if
<ul>
<li>{@code x} is infinite or NaN
<li>{@code x}, after being rounded to a mathematical integer using the specified rounding
mode, is either less than {@code Long.MIN_VALUE} or greater than {@code
Long.MAX_VALUE}
<li>{@code x} is not a mathematical integer and {@code mode} is {@link
RoundingMode#UNNECESSARY}
</ul>

Returns the { @code long } value that is equal to { @code x } rounded with the specified rounding mode if possible .


@GwtIncompatible
  public static BigInteger roundToBigInteger(double x, RoundingMode mode) {
    x = roundIntermediate(x, mode);
    if (MIN_LONG_AS_DOUBLE - x < 1.0 & x < MAX_LONG_AS_DOUBLE_PLUS_ONE) {
      return BigInteger.valueOf((long) x);
    }
    int exponent = getExponent(x);
    long significand = getSignificand(x);
    BigInteger result = BigInteger.valueOf(significand).shiftLeft(exponent - SIGNIFICAND_BITS);
    return (x < 0) ? result.negate() : result;
  }

@ GwtIncompatible public static BigInteger roundToBigInteger ( double x , RoundingMode mode ) { x = roundIntermediate ( x , mode ) ; if ( MIN_LONG_AS_DOUBLE - x < 1.0 & x < MAX_LONG_AS_DOUBLE_PLUS_ONE ) { return BigInteger . valueOf ( ( long ) x ) ; } int exponent = getExponent ( x ) ; long significand = getSignificand ( x ) ; BigInteger result = BigInteger . valueOf ( significand ) . shiftLeft ( exponent - SIGNIFICAND_BITS ) ; return ( x < 0 ) ? result . negate ( ) : result ; }

#roundIntermediate java . lang . Math . getExponent com . google . common . math . DoubleUtils


@GwtIncompatible // com.google.common.math.DoubleUtils
  public static boolean isPowerOfTwo(double x) {
    if (x > 0.0 && isFinite(x)) {
      long significand = getSignificand(x);
      return (significand & (significand - 1)) == 0;
    }
    return false;
  }

@
GwtIncompatible
// com.google.common.math.DoubleUtils
public
static
boolean
isPowerOfTwo
(
double
x
)
{
if
(
x
>
0.0
&&
isFinite
(
x
)
)
{
long
significand
=
getSignificand
(
x
)
;
return
(
significand
&
(
significand
1
)
)
==
0
;
}
return
false
;
}

Returns {@code true} if {@code x} is exactly equal to {@code 2^k} for some finite integer
{@code k}.


public static boolean fuzzyEquals(double a, double b, double tolerance) {
    MathPreconditions.checkNonNegative("tolerance", tolerance);
    return Math.copySign(a - b, 1.0) <= tolerance
        // copySign(x, 1.0) is a branch-free version of abs(x), but with different NaN semantics
        || (a == b) // needed to ensure that infinities equal themselves
        || (Double.isNaN(a) && Double.isNaN(b));
  }

Returns {@code true} if {@code a} and {@code b} are within {@code tolerance} of each other.

Technically speaking, this is equivalent to {@code Math.abs(a - b) <= tolerance ||
Double.valueOf(a).equals(Double.valueOf(b))}.

Notable special cases include:

All NaNs are fuzzily equal.

If {@code a == b}, then {@code a} and {@code b} are always fuzzily equal.

Positive and negative zero are always fuzzily equal.

If {@code tolerance} is zero, and neither {@code a} nor {@code b} is NaN, then {@code a}
and {@code b} are fuzzily equal if and only if {@code a == b}.

With {@link Double#POSITIVE_INFINITY} tolerance, all non-NaN values are fuzzily equal.

With finite tolerance, {@code Double.POSITIVE_INFINITY} and {@code
Double.NEGATIVE_INFINITY} are fuzzily equal only to themselves.

This is reflexive and symmetric, but not transitive, so it is not an
equivalence relation and not suitable for use in {@link Object#equals}
implementations.

@throws IllegalArgumentException if {@code tolerance} is {@code < 0} or NaN
@since 13.0

Returns { @code true } if { @code a } and { @code b } are within { @code tolerance } of each other .


public static int fuzzyCompare(double a, double b, double tolerance) {
    if (fuzzyEquals(a, b, tolerance)) {
      return 0;
    } else if (a < b) {
      return -1;
    } else if (a > b) {
      return 1;
    } else {
      return Booleans.compare(Double.isNaN(a), Double.isNaN(b));
    }
  }

public static int fuzzyCompare ( double a , double b , double tolerance ) { if ( fuzzyEquals ( a , b , tolerance ) ) { return 0 ; } else if ( a < b ) { return - 1 ; } else if ( a > b ) { return 1 ; } else { return Booleans . compare ( Double . isNaN ( a ) , Double . isNaN ( b ) ) ; } }

Compares {@code a} and {@code b} "fuzzily," with a tolerance for nearly-equal values.

This method is equivalent to {@code fuzzyEquals(a, b, tolerance) ? 0 : Double.compare(a,
b)}. In particular, like {@link Double#compare(double, double)}, it treats all NaN values as
equal and greater than all other values (including {@link Double#POSITIVE_INFINITY}).

This is not a total ordering and is not suitable for use in {@link
Comparable#compareTo} implementations. In particular, it is not transitive.

@throws IllegalArgumentException if {@code tolerance} is {@code < 0} or NaN
@since 13.0

Compares { @code a } and { @code b } fuzzily with a tolerance for nearly - equal values .


@Deprecated
  // com.google.common.math.DoubleUtils
  @GwtIncompatible
  public static double mean(double... values) {
    checkArgument(values.length > 0, "Cannot take mean of 0 values");
    long count = 1;
    double mean = checkFinite(values[0]);
    for (int index = 1; index < values.length; ++index) {
      checkFinite(values[index]);
      count++;
      // Art of Computer Programming vol. 2, Knuth, 4.2.2, (15)
      mean += (values[index] - mean) / count;
    }
    return mean;
  }

Returns the arithmetic mean of
{@code values}.

If these values are a sample drawn from a population, this is also an unbiased estimator of
the arithmetic mean of the population.

@param values a nonempty series of values
@throws IllegalArgumentException if {@code values} is empty or contains any non-finite value
@deprecated Use {@link Stats#meanOf} instead, noting the less strict handling of non-finite
values.

Returns the <a href = http : // en . wikipedia . org / wiki / Arithmetic_mean > arithmetic mean< / a > of { @code values } .


@Deprecated
  public static double mean(int... values) {
    checkArgument(values.length > 0, "Cannot take mean of 0 values");
    // The upper bound on the the length of an array and the bounds on the int values mean that, in
    // this case only, we can compute the sum as a long without risking overflow or loss of
    // precision. So we do that, as it's slightly quicker than the Knuth algorithm.
    long sum = 0;
    for (int index = 0; index < values.length; ++index) {
      sum += values[index];
    }
    return (double) sum / values.length;
  }

Returns the arithmetic mean of
{@code values}.

If these values are a sample drawn from a population, this is also an unbiased estimator of
the arithmetic mean of the population.

@param values a nonempty series of values
@throws IllegalArgumentException if {@code values} is empty
@deprecated Use {@link Stats#meanOf} instead, noting the less strict handling of non-finite
values.


@Deprecated
  public static double mean(long... values) {
    checkArgument(values.length > 0, "Cannot take mean of 0 values");
    long count = 1;
    double mean = values[0];
    for (int index = 1; index < values.length; ++index) {
      count++;
      // Art of Computer Programming vol. 2, Knuth, 4.2.2, (15)
      mean += (values[index] - mean) / count;
    }
    return mean;
  }

Returns the arithmetic mean of
{@code values}.

If these values are a sample drawn from a population, this is also an unbiased estimator of
the arithmetic mean of the population.

@param values a nonempty series of values, which will be converted to {@code double} values
(this may cause loss of precision for longs of magnitude over 2^53 (slightly over 9e15))
@throws IllegalArgumentException if {@code values} is empty
@deprecated Use {@link Stats#meanOf} instead, noting the less strict handling of non-finite
values.


private void removeNode(Node<K, V> node) {
    if (node.previous != null) {
      node.previous.next = node.next;
    } else { // node was head
      head = node.next;
    }
    if (node.next != null) {
      node.next.previous = node.previous;
    } else { // node was tail
      tail = node.previous;
    }
    if (node.previousSibling == null && node.nextSibling == null) {
      KeyList<K, V> keyList = keyToKeyList.remove(node.key);
      keyList.count = 0;
      modCount++;
    } else {
      KeyList<K, V> keyList = keyToKeyList.get(node.key);
      keyList.count--;

      if (node.previousSibling == null) {
        keyList.head = node.nextSibling;
      } else {
        node.previousSibling.nextSibling = node.nextSibling;
      }

      if (node.nextSibling == null) {
        keyList.tail = node.previousSibling;
      } else {
        node.nextSibling.previousSibling = node.previousSibling;
      }
    }
    size--;
  }

private
void
removeNode
(
Node
<
K
,
V
>
node
)
{
if
(
node
.
previous
!=
)
{
node
.
previous
.
next
=
node
.
next
;
}
else
{
// node was head
head
=
node
.
next
;
}
if
(
node
.
next
!=
)
{
node
.
next
.
previous
=
node
.
previous
;
}
else
{
// node was tail
tail
=
node
.
previous
;
}
if
(
node
.
previousSibling
==
&&
node
.
nextSibling
==
)
{
KeyList
<
K
,
V
>
keyList
=
keyToKeyList
.
remove
(
node
.
key
)
;
keyList
.
count
=
0
;
modCount
++
;
}
else
{
KeyList
<
K
,
V
>
keyList
=
keyToKeyList
.
get
(
node
.
key
)
;
keyList
.
count
;
if
(
node
.
previousSibling
==
)
{
keyList
.
head
=
node
.
nextSibling
;
}
else
{
node
.
previousSibling
.
nextSibling
=
node
.
nextSibling
;
}
if
(
node
.
nextSibling
==
)
{
keyList
.
tail
=
node
.
previousSibling
;
}
else
{
node
.
nextSibling
.
previousSibling
=
node
.
previousSibling
;
}
}
size
;
}

Removes the specified node from the linked list. This method is only intended to be used from
the {@code Iterator} classes. See also {@link LinkedListMultimap#removeAllNodes(Object)}.

Removes the specified node from the linked list . This method is only intended to be used from the {


@CanIgnoreReturnValue
  @Override
  public List<V> replaceValues(@Nullable K key, Iterable<? extends V> values) {
    List<V> oldValues = getCopy(key);
    ListIterator<V> keyValues = new ValueForKeyIterator(key);
    Iterator<? extends V> newValues = values.iterator();

    // Replace existing values, if any.
    while (keyValues.hasNext() && newValues.hasNext()) {
      keyValues.next();
      keyValues.set(newValues.next());
    }

    // Remove remaining old values, if any.
    while (keyValues.hasNext()) {
      keyValues.next();
      keyValues.remove();
    }

    // Add remaining new values, if any.
    while (newValues.hasNext()) {
      keyValues.add(newValues.next());
    }

    return oldValues;
  }

@
CanIgnoreReturnValue
@
Override
public
List
<
V
>
replaceValues
(
@
Nullable
K
key
,
Iterable
<
extends
V
>
values
)
{
List
<
V
>
oldValues
=
getCopy
(
key
)
;
ListIterator
<
V
>
keyValues
=
new
ValueForKeyIterator
(
key
)
;
Iterator
<
extends
V
>
newValues
=
values
.
iterator
(
)
;
// Replace existing values, if any.
while
(
keyValues
.
hasNext
(
)
&&
newValues
.
hasNext
(
)
)
{
keyValues
.
next
(
)
;
keyValues
.
set
(
newValues
.
next
(
)
)
;
}
// Remove remaining old values, if any.
while
(
keyValues
.
hasNext
(
)
)
{
keyValues
.
next
(
)
;
keyValues
.
remove
(
)
;
}
// Add remaining new values, if any.
while
(
newValues
.
hasNext
(
)
)
{
keyValues
.
add
(
newValues
.
next
(
)
)
;
}
return
oldValues
;
}

{@inheritDoc}

If any entries for the specified {@code key} already exist in the multimap, their values are
changed in-place without affecting the iteration order.

The returned list is immutable and implements {@link java.util.RandomAccess}.


@Override
  public List<V> get(final @Nullable K key) {
    return new AbstractSequentialList<V>() {
      @Override
      public int size() {
        KeyList<K, V> keyList = keyToKeyList.get(key);
        return (keyList == null) ? 0 : keyList.count;
      }

      @Override
      public ListIterator<V> listIterator(int index) {
        return new ValueForKeyIterator(key, index);
      }
    };
  }

@ Override public List < V > get ( final @ Nullable K key ) { return new AbstractSequentialList < V > ( ) { @ Override public int size ( ) { KeyList < K , V > keyList = keyToKeyList . get ( key ) ; return ( keyList == null ) ? 0 : keyList . count ; } @ Override public ListIterator < V > listIterator ( int index ) { return new ValueForKeyIterator ( key , index ) ; } } ; }

{@inheritDoc}

If the multimap is modified while an iteration over the list is in progress (except through
the iterator's own {@code add}, {@code set} or {@code remove} operations) the results of the
iteration are undefined.

The returned list is not serializable and does not have random access.


@Override
  public List<Entry<K, V>> entries() {
    return (List<Entry<K, V>>) super.entries();
  }

@ Override public List < Entry < K , V > > entries ( ) { return ( List < Entry < K , V > > ) super . entries ( ) ; }

{@inheritDoc}

The iterator generated by the returned collection traverses the entries in the order they
were added to the multimap. Because the entries may have duplicates and follow the insertion
ordering, this method returns a {@link List}, instead of the {@link Collection} specified in
the {@link ListMultimap} interface.

An entry's {@link Entry#getKey} method always returns the same key, regardless of what
happens subsequently. As long as the corresponding key-value mapping is not removed from the
multimap, {@link Entry#getValue} returns the value from the multimap, which may change over
time, and {@link Entry#setValue} modifies that value. Removing the mapping from the multimap
does not alter the value returned by {@code getValue()}, though a subsequent {@code setValue()}
call won't update the multimap but will lead to a revised value being returned by {@code
getValue()}.


@Override
  @CanIgnoreReturnValue
  public int read() throws IOException {
    int b = in.read();
    if (b != -1) {
      hasher.putByte((byte) b);
    }
    return b;
  }

@ Override @ CanIgnoreReturnValue public int read ( ) throws IOException { int b = in . read ( ) ; if ( b != - 1 ) { hasher . putByte ( ( byte ) b ) ; } return b ; }

Reads the next byte of data from the underlying input stream and updates the hasher with the
byte read.

Reads the next byte of data from the underlying input stream and updates the hasher with the byte read .


@Override
  @CanIgnoreReturnValue
  public int read(byte[] bytes, int off, int len) throws IOException {
    int numOfBytesRead = in.read(bytes, off, len);
    if (numOfBytesRead != -1) {
      hasher.putBytes(bytes, off, numOfBytesRead);
    }
    return numOfBytesRead;
  }

@ Override @ CanIgnoreReturnValue public int read ( byte [ ] bytes , int off , int len ) throws IOException { int numOfBytesRead = in . read ( bytes , off , len ) ; if ( numOfBytesRead != - 1 ) { hasher . putBytes ( bytes , off , numOfBytesRead ) ; } return numOfBytesRead ; }

Reads the specified bytes of data from the underlying input stream and updates the hasher with
the bytes read.

Reads the specified bytes of data from the underlying input stream and updates the hasher with the bytes read .


static <K, V> void writeMap(Map<K, V> map, ObjectOutputStream stream) throws IOException {
    stream.writeInt(map.size());
    for (Map.Entry<K, V> entry : map.entrySet()) {
      stream.writeObject(entry.getKey());
      stream.writeObject(entry.getValue());
    }
  }

static < K , V > void writeMap ( Map < K , V > map , ObjectOutputStream stream ) throws IOException { stream . writeInt ( map . size ( ) ) ; for ( Map . Entry < K , V > entry : map . entrySet ( ) ) { stream . writeObject ( entry . getKey ( ) ) ; stream . writeObject ( entry . getValue ( ) ) ; } }

Stores the contents of a map in an output stream, as part of serialization. It does not support
concurrent maps whose content may change while the method is running.

<p>The serialized output consists of the number of entries, first key, first value, second key,
second value, and so on.

Stores the contents of a map in an output stream as part of serialization . It does not support concurrent maps whose content may change while the method is running .


static <K, V> void populateMap(Map<K, V> map, ObjectInputStream stream)
      throws IOException, ClassNotFoundException {
    int size = stream.readInt();
    populateMap(map, stream, size);
  }

static < K , V > void populateMap ( Map < K , V > map , ObjectInputStream stream ) throws IOException , ClassNotFoundException { int size = stream . readInt ( ) ; populateMap ( map , stream , size ) ; }

Populates a map by reading an input stream, as part of deserialization. See {@link #writeMap}
for the data format.

Populates a map by reading an input stream as part of deserialization . See {


static <K, V> void populateMap(Map<K, V> map, ObjectInputStream stream, int size)
      throws IOException, ClassNotFoundException {
    for (int i = 0; i < size; i++) {
      @SuppressWarnings("unchecked") // reading data stored by writeMap
      K key = (K) stream.readObject();
      @SuppressWarnings("unchecked") // reading data stored by writeMap
      V value = (V) stream.readObject();
      map.put(key, value);
    }
  }

static
<
K
,
V
>
void
populateMap
(
Map
<
K
,
V
>
map
,
ObjectInputStream
stream
,
int
size
)
throws
IOException
,
ClassNotFoundException
{
for
(
int
i
=
0
;
i
<
size
;
i
++
)
{
@
SuppressWarnings
(
"unchecked"
)
// reading data stored by writeMap
K
key
=
(
K
)
stream
.
readObject
(
)
;
@
SuppressWarnings
(
"unchecked"
)
// reading data stored by writeMap
V
value
=
(
V
)
stream
.
readObject
(
)
;
map
.
put
(
key
,
value
)
;
}
}

Populates a map by reading an input stream, as part of deserialization. See {@link #writeMap}
for the data format. The size is determined by a prior call to {@link #readCount}.


static <E> void writeMultiset(Multiset<E> multiset, ObjectOutputStream stream)
      throws IOException {
    int entryCount = multiset.entrySet().size();
    stream.writeInt(entryCount);
    for (Multiset.Entry<E> entry : multiset.entrySet()) {
      stream.writeObject(entry.getElement());
      stream.writeInt(entry.getCount());
    }
  }

static < E > void writeMultiset ( Multiset < E > multiset , ObjectOutputStream stream ) throws IOException { int entryCount = multiset . entrySet ( ) . size ( ) ; stream . writeInt ( entryCount ) ; for ( Multiset . Entry < E > entry : multiset . entrySet ( ) ) { stream . writeObject ( entry . getElement ( ) ) ; stream . writeInt ( entry . getCount ( ) ) ; } }

Stores the contents of a multiset in an output stream, as part of serialization. It does not
support concurrent multisets whose content may change while the method is running.

<p>The serialized output consists of the number of distinct elements, the first element, its
count, the second element, its count, and so on.

Stores the contents of a multiset in an output stream as part of serialization . It does not support concurrent multisets whose content may change while the method is running .


static <E> void populateMultiset(Multiset<E> multiset, ObjectInputStream stream)
      throws IOException, ClassNotFoundException {
    int distinctElements = stream.readInt();
    populateMultiset(multiset, stream, distinctElements);
  }

static < E > void populateMultiset ( Multiset < E > multiset , ObjectInputStream stream ) throws IOException , ClassNotFoundException { int distinctElements = stream . readInt ( ) ; populateMultiset ( multiset , stream , distinctElements ) ; }

Populates a multiset by reading an input stream, as part of deserialization. See {@link
#writeMultiset} for the data format.

Populates a multiset by reading an input stream as part of deserialization . See {


static <E> void populateMultiset(
      Multiset<E> multiset, ObjectInputStream stream, int distinctElements)
      throws IOException, ClassNotFoundException {
    for (int i = 0; i < distinctElements; i++) {
      @SuppressWarnings("unchecked") // reading data stored by writeMultiset
      E element = (E) stream.readObject();
      int count = stream.readInt();
      multiset.add(element, count);
    }
  }

static
<
E
>
void
populateMultiset
(
Multiset
<
E
>
multiset
,
ObjectInputStream
stream
,
int
distinctElements
)
throws
IOException
,
ClassNotFoundException
{
for
(
int
i
=
0
;
i
<
distinctElements
;
i
++
)
{
@
SuppressWarnings
(
"unchecked"
)
// reading data stored by writeMultiset
E
element
=
(
E
)
stream
.
readObject
(
)
;
int
count
=
stream
.
readInt
(
)
;
multiset
.
add
(
element
,
count
)
;
}
}

Populates a multiset by reading an input stream, as part of deserialization. See {@link
#writeMultiset} for the data format. The number of distinct elements is determined by a prior
call to {@link #readCount}.


static <K, V> void writeMultimap(Multimap<K, V> multimap, ObjectOutputStream stream)
      throws IOException {
    stream.writeInt(multimap.asMap().size());
    for (Map.Entry<K, Collection<V>> entry : multimap.asMap().entrySet()) {
      stream.writeObject(entry.getKey());
      stream.writeInt(entry.getValue().size());
      for (V value : entry.getValue()) {
        stream.writeObject(value);
      }
    }
  }

static < K , V > void writeMultimap ( Multimap < K , V > multimap , ObjectOutputStream stream ) throws IOException { stream . writeInt ( multimap . asMap ( ) . size ( ) ) ; for ( Map . Entry < K , Collection < V > > entry : multimap . asMap ( ) . entrySet ( ) ) { stream . writeObject ( entry . getKey ( ) ) ; stream . writeInt ( entry . getValue ( ) . size ( ) ) ; for ( V value : entry . getValue ( ) ) { stream . writeObject ( value ) ; } } }

Stores the contents of a multimap in an output stream, as part of serialization. It does not
support concurrent multimaps whose content may change while the method is running. The {@link
Multimap#asMap} view determines the ordering in which data is written to the stream.

<p>The serialized output consists of the number of distinct keys, and then for each distinct
key: the key, the number of values for that key, and the key's values.

Stores the contents of a multimap in an output stream as part of serialization . It does not support concurrent multimaps whose content may change while the method is running . The { @link Multimap#asMap } view determines the ordering in which data is written to the stream .


static <K, V> void populateMultimap(Multimap<K, V> multimap, ObjectInputStream stream)
      throws IOException, ClassNotFoundException {
    int distinctKeys = stream.readInt();
    populateMultimap(multimap, stream, distinctKeys);
  }

static < K , V > void populateMultimap ( Multimap < K , V > multimap , ObjectInputStream stream ) throws IOException , ClassNotFoundException { int distinctKeys = stream . readInt ( ) ; populateMultimap ( multimap , stream , distinctKeys ) ; }

Populates a multimap by reading an input stream, as part of deserialization. See {@link
#writeMultimap} for the data format.

Populates a multimap by reading an input stream as part of deserialization . See {


static <K, V> void populateMultimap(
      Multimap<K, V> multimap, ObjectInputStream stream, int distinctKeys)
      throws IOException, ClassNotFoundException {
    for (int i = 0; i < distinctKeys; i++) {
      @SuppressWarnings("unchecked") // reading data stored by writeMultimap
      K key = (K) stream.readObject();
      Collection<V> values = multimap.get(key);
      int valueCount = stream.readInt();
      for (int j = 0; j < valueCount; j++) {
        @SuppressWarnings("unchecked") // reading data stored by writeMultimap
        V value = (V) stream.readObject();
        values.add(value);
      }
    }
  }

static
<
K
,
V
>
void
populateMultimap
(
Multimap
<
K
,
V
>
multimap
,
ObjectInputStream
stream
,
int
distinctKeys
)
throws
IOException
,
ClassNotFoundException
{
for
(
int
i
=
0
;
i
<
distinctKeys
;
i
++
)
{
@
SuppressWarnings
(
"unchecked"
)
// reading data stored by writeMultimap
K
key
=
(
K
)
stream
.
readObject
(
)
;
Collection
<
V
>
values
=
multimap
.
get
(
key
)
;
int
valueCount
=
stream
.
readInt
(
)
;
for
(
int
j
=
0
;
j
<
valueCount
;
j
++
)
{
@
SuppressWarnings
(
"unchecked"
)
// reading data stored by writeMultimap
V
value
=
(
V
)
stream
.
readObject
(
)
;
values
.
add
(
value
)
;
}
}
}

Populates a multimap by reading an input stream, as part of deserialization. See {@link
#writeMultimap} for the data format. The number of distinct keys is determined by a prior call
to {@link #readCount}.


static <T> FieldSetter<T> getFieldSetter(final Class<T> clazz, String fieldName) {
    try {
      Field field = clazz.getDeclaredField(fieldName);
      return new FieldSetter<T>(field);
    } catch (NoSuchFieldException e) {
      throw new AssertionError(e); // programmer error
    }
  }

static
<
T
>
FieldSetter
<
T
>
getFieldSetter
(
final
Class
<
T
>
clazz
,
String
fieldName
)
{
try
{
Field
field
=
clazz
.
getDeclaredField
(
fieldName
)
;
return
new
FieldSetter
<
T
>
(
field
)
;
}
catch
(
NoSuchFieldException
e
)
{
throw
new
AssertionError
(
e
)
;
// programmer error
}
}

Secret sauce for setting final fields; don't make it public.

Secret sauce for setting final fields ; don t make it public .


@Override
  protected V getIfCached(@Nullable Object key) {
    V value = super.getIfCached(key);
    if (value != null) {
      return value;
    }

    // Store a local reference to the cache entry. If the backing map is immutable, this,
    // in combination with immutable cache entries, will ensure a thread-safe cache.
    CacheEntry<K, V> entry;

    // Check cache. We use == on purpose because it's cheaper and a cache miss is ok.
    entry = cacheEntry1;
    if (entry != null && entry.key == key) {
      return entry.value;
    }
    entry = cacheEntry2;
    if (entry != null && entry.key == key) {
      // Promote second cache entry to first so the access pattern
      // [K1, K2, K1, K3, K1, K4...] still hits the cache half the time.
      addToCache(entry);
      return entry.value;
    }
    return null;
  }

Internal methods ('protected' is still package-visible, but treat as only subclass-visible)

Internal methods ( protected is still package - visible but treat as only subclass - visible )


protected void processRemaining(ByteBuffer bb) {
    bb.position(bb.limit()); // move at the end
    bb.limit(chunkSize + 7); // get ready to pad with longs
    while (bb.position() < chunkSize) {
      bb.putLong(0);
    }
    bb.limit(chunkSize);
    bb.flip();
    process(bb);
  }

protected
void
processRemaining
(
ByteBuffer
bb
)
{
bb
.
position
(
bb
.
limit
(
)
)
;
// move at the end
bb
.
limit
(
chunkSize
+
7
)
;
// get ready to pad with longs
while
(
bb
.
position
(
)
<
chunkSize
)
{
bb
.
putLong
(
0
)
;
}
bb
.
limit
(
chunkSize
)
;
bb
.
flip
(
)
;
process
(
bb
)
;
}

This is invoked for the last bytes of the input, which are not enough to fill a whole chunk.
The passed {@code ByteBuffer} is guaranteed to be non-empty.

<p>This implementation simply pads with zeros and delegates to {@link #process(ByteBuffer)}.

This is invoked for the last bytes of the input which are not enough to fill a whole chunk . The passed { @code ByteBuffer } is guaranteed to be non - empty .


public UnsignedLong dividedBy(UnsignedLong val) {
    return fromLongBits(UnsignedLongs.divide(value, checkNotNull(val).value));
  }

public UnsignedLong dividedBy ( UnsignedLong val ) { return fromLongBits ( UnsignedLongs . divide ( value , checkNotNull ( val ) . value ) ) ; }

Returns the result of dividing this by {@code val}.

@since 14.0

Returns the result of dividing this by { @code val } .


public UnsignedLong mod(UnsignedLong val) {
    return fromLongBits(UnsignedLongs.remainder(value, checkNotNull(val).value));
  }

public UnsignedLong mod ( UnsignedLong val ) { return fromLongBits ( UnsignedLongs . remainder ( value , checkNotNull ( val ) . value ) ) ; }

Returns this modulo {@code val}.

@since 14.0


@Override
  public float floatValue() {
    @SuppressWarnings("cast")
    float fValue = (float) (value & UNSIGNED_MASK);
    if (value < 0) {
      fValue += 0x1.0p63f;
    }
    return fValue;
  }

@ Override public float floatValue ( ) { @ SuppressWarnings ( "cast" ) float fValue = ( float ) ( value & UNSIGNED_MASK ) ; if ( value < 0 ) { fValue += 0x1 . 0 p63f ; } return fValue ; }

Returns the value of this {@code UnsignedLong} as a {@code float}, analogous to a widening
primitive conversion from {@code long} to {@code float}, and correctly rounded.


@Override
  public double doubleValue() {
    @SuppressWarnings("cast")
    double dValue = (double) (value & UNSIGNED_MASK);
    if (value < 0) {
      dValue += 0x1.0p63;
    }
    return dValue;
  }

@ Override public double doubleValue ( ) { @ SuppressWarnings ( "cast" ) double dValue = ( double ) ( value & UNSIGNED_MASK ) ; if ( value < 0 ) { dValue += 0x1 . 0 p63 ; } return dValue ; }

Returns the value of this {@code UnsignedLong} as a {@code double}, analogous to a widening
primitive conversion from {@code long} to {@code double}, and correctly rounded.


public BigInteger bigIntegerValue() {
    BigInteger bigInt = BigInteger.valueOf(value & UNSIGNED_MASK);
    if (value < 0) {
      bigInt = bigInt.setBit(Long.SIZE - 1);
    }
    return bigInt;
  }

public BigInteger bigIntegerValue ( ) { BigInteger bigInt = BigInteger . valueOf ( value & UNSIGNED_MASK ) ; if ( value < 0 ) { bigInt = bigInt . setBit ( Long . SIZE - 1 ) ; } return bigInt ; }

Returns the value of this {@code UnsignedLong} as a {@link BigInteger}.


@GwtIncompatible // Class.cast, Class.isInstance
  public static <X extends Throwable> void throwIfInstanceOf(
      Throwable throwable, Class<X> declaredType) throws X {
    checkNotNull(throwable);
    if (declaredType.isInstance(throwable)) {
      throw declaredType.cast(throwable);
    }
  }

@
GwtIncompatible
// Class.cast, Class.isInstance
public
static
<
X
extends
Throwable
>
void
throwIfInstanceOf
(
Throwable
throwable
,
Class
<
X
>
declaredType
)
throws
X
{
checkNotNull
(
throwable
)
;
if
(
declaredType
.
isInstance
(
throwable
)
)
{
throw
declaredType
.
cast
(
throwable
)
;
}
}

Throws {@code throwable} if it is an instance of {@code declaredType}. Example usage:

<pre>
for (Foo foo : foos) {
try {
foo.bar();
} catch (BarException | RuntimeException | Error t) {
failure = t;
}
}
if (failure != null) {
throwIfInstanceOf(failure, BarException.class);
throwIfUnchecked(failure);
throw new AssertionError(failure);
}
</pre>

@since 20.0

Throws { @code throwable } if it is an instance of { @code declaredType } . Example usage :


@Deprecated
  @GwtIncompatible // throwIfInstanceOf
  public static <X extends Throwable> void propagateIfInstanceOf(
      @Nullable Throwable throwable, Class<X> declaredType) throws X {
    if (throwable != null) {
      throwIfInstanceOf(throwable, declaredType);
    }
  }

@
Deprecated
@
GwtIncompatible
// throwIfInstanceOf
public
static
<
X
extends
Throwable
>
void
propagateIfInstanceOf
(
@
Nullable
Throwable
throwable
,
Class
<
X
>
declaredType
)
throws
X
{
if
(
throwable
!=
)
{
throwIfInstanceOf
(
throwable
,
declaredType
)
;
}
}

Propagates {@code throwable} exactly as-is, if and only if it is an instance of {@code
declaredType}. Example usage:

<pre>
try {
someMethodThatCouldThrowAnything();
} catch (IKnowWhatToDoWithThisException e) {
handle(e);
} catch (Throwable t) {
Throwables.propagateIfInstanceOf(t, IOException.class);
Throwables.propagateIfInstanceOf(t, SQLException.class);
throw Throwables.propagate(t);
}
</pre>

@deprecated Use {@link #throwIfInstanceOf}, which has the same behavior but rejects {@code
null}.

Propagates { @code throwable } exactly as - is if and only if it is an instance of { @code declaredType } . Example usage :


public static void throwIfUnchecked(Throwable throwable) {
    checkNotNull(throwable);
    if (throwable instanceof RuntimeException) {
      throw (RuntimeException) throwable;
    }
    if (throwable instanceof Error) {
      throw (Error) throwable;
    }
  }

public static void throwIfUnchecked ( Throwable throwable ) { checkNotNull ( throwable ) ; if ( throwable instanceof RuntimeException ) { throw ( RuntimeException ) throwable ; } if ( throwable instanceof Error ) { throw ( Error ) throwable ; } }

Throws {@code throwable} if it is a {@link RuntimeException} or {@link Error}. Example usage:

<pre>
for (Foo foo : foos) {
try {
foo.bar();
} catch (RuntimeException | Error t) {
failure = t;
}
}
if (failure != null) {
throwIfUnchecked(failure);
throw new AssertionError(failure);
}
</pre>

@since 20.0

Throws { @code throwable } if it is a { @link RuntimeException } or { @link Error } . Example usage :


@Deprecated
  @GwtIncompatible
  public static void propagateIfPossible(@Nullable Throwable throwable) {
    if (throwable != null) {
      throwIfUnchecked(throwable);
    }
  }

@ Deprecated @ GwtIncompatible public static void propagateIfPossible ( @ Nullable Throwable throwable ) { if ( throwable != null ) { throwIfUnchecked ( throwable ) ; } }

Propagates {@code throwable} exactly as-is, if and only if it is an instance of {@link
RuntimeException} or {@link Error}. Example usage:

<pre>
try {
someMethodThatCouldThrowAnything();
} catch (IKnowWhatToDoWithThisException e) {
handle(e);
} catch (Throwable t) {
Throwables.propagateIfPossible(t);
throw new RuntimeException("unexpected", t);
}
</pre>

@deprecated Use {@link #throwIfUnchecked}, which has the same behavior but rejects {@code
null}.

Propagates { @code throwable } exactly as - is if and only if it is an instance of { @link RuntimeException } or { @link Error } . Example usage :


@GwtIncompatible // propagateIfInstanceOf
  public static <X1 extends Throwable, X2 extends Throwable> void propagateIfPossible(
      @Nullable Throwable throwable, Class<X1> declaredType1, Class<X2> declaredType2)
      throws X1, X2 {
    checkNotNull(declaredType2);
    propagateIfInstanceOf(throwable, declaredType1);
    propagateIfPossible(throwable, declaredType2);
  }

@
GwtIncompatible
// propagateIfInstanceOf
public
static
<
X1
extends
Throwable
,
X2
extends
Throwable
>
void
propagateIfPossible
(
@
Nullable
Throwable
throwable
,
Class
<
X1
>
declaredType1
,
Class
<
X2
>
declaredType2
)
throws
X1
,
X2
{
checkNotNull
(
declaredType2
)
;
propagateIfInstanceOf
(
throwable
,
declaredType1
)
;
propagateIfPossible
(
throwable
,
declaredType2
)
;
}

Propagates {@code throwable} exactly as-is, if and only if it is an instance of {@link
RuntimeException}, {@link Error}, {@code declaredType1}, or {@code declaredType2}. In the
unlikely case that you have three or more declared checked exception types, you can handle them
all by invoking these methods repeatedly. See usage example in {@link
#propagateIfPossible(Throwable, Class)}.

@param throwable the Throwable to possibly propagate
@param declaredType1 any checked exception type declared by the calling method
@param declaredType2 any other checked exception type declared by the calling method

Propagates { @code throwable } exactly as - is if and only if it is an instance of { @link RuntimeException } { @link Error } { @code declaredType1 } or { @code declaredType2 } . In the unlikely case that you have three or more declared checked exception types you can handle them all by invoking these methods repeatedly . See usage example in { @link #propagateIfPossible ( Throwable Class ) } .


@CanIgnoreReturnValue
  @GwtIncompatible
  @Deprecated
  public static RuntimeException propagate(Throwable throwable) {
    throwIfUnchecked(throwable);
    throw new RuntimeException(throwable);
  }

@ CanIgnoreReturnValue @ GwtIncompatible @ Deprecated public static RuntimeException propagate ( Throwable throwable ) { throwIfUnchecked ( throwable ) ; throw new RuntimeException ( throwable ) ; }

Propagates {@code throwable} as-is if it is an instance of {@link RuntimeException} or {@link
Error}, or else as a last resort, wraps it in a {@code RuntimeException} and then propagates.

This method always throws an exception. The {@code RuntimeException} return type allows
client code to signal to the compiler that statements after the call are unreachable. Example
usage:

T doSomething() {
try {
return someMethodThatCouldThrowAnything();
} catch (IKnowWhatToDoWithThisException e) {
return handle(e);
} catch (Throwable t) {
throw Throwables.propagate(t);
}
}

@param throwable the Throwable to propagate
@return nothing will ever be returned; this return type is only for your convenience, as
illustrated in the example above
@deprecated Use {@code throw e} or {@code throw new RuntimeException(e)} directly, or use a
combination of {@link #throwIfUnchecked} and {@code throw new RuntimeException(e)}. For
background on the deprecation, read Why we deprecated
{@code Throwables.propagate}.

Propagates { @code throwable } as - is if it is an instance of { @link RuntimeException } or { @link Error } or else as a last resort wraps it in a { @code RuntimeException } and then propagates .


public static Throwable getRootCause(Throwable throwable) {
    // Keep a second pointer that slowly walks the causal chain. If the fast pointer ever catches
    // the slower pointer, then there's a loop.
    Throwable slowPointer = throwable;
    boolean advanceSlowPointer = false;

    Throwable cause;
    while ((cause = throwable.getCause()) != null) {
      throwable = cause;

      if (throwable == slowPointer) {
        throw new IllegalArgumentException("Loop in causal chain detected.", throwable);
      }
      if (advanceSlowPointer) {
        slowPointer = slowPointer.getCause();
      }
      advanceSlowPointer = !advanceSlowPointer; // only advance every other iteration
    }
    return throwable;
  }

Returns the innermost cause of {@code throwable}. The first throwable in a chain provides
context from when the error or exception was initially detected. Example usage:

<pre>
assertEquals("Unable to assign a customer id", Throwables.getRootCause(e).getMessage());
</pre>

@throws IllegalArgumentException if there is a loop in the causal chain

Returns the innermost cause of { @code throwable } . The first throwable in a chain provides context from when the error or exception was initially detected . Example usage :


@Beta // TODO(kevinb): decide best return type
  public static List<Throwable> getCausalChain(Throwable throwable) {
    checkNotNull(throwable);
    List<Throwable> causes = new ArrayList<>(4);
    causes.add(throwable);

    // Keep a second pointer that slowly walks the causal chain. If the fast pointer ever catches
    // the slower pointer, then there's a loop.
    Throwable slowPointer = throwable;
    boolean advanceSlowPointer = false;

    Throwable cause;
    while ((cause = throwable.getCause()) != null) {
      throwable = cause;
      causes.add(throwable);

      if (throwable == slowPointer) {
        throw new IllegalArgumentException("Loop in causal chain detected.", throwable);
      }
      if (advanceSlowPointer) {
        slowPointer = slowPointer.getCause();
      }
      advanceSlowPointer = !advanceSlowPointer; // only advance every other iteration
    }
    return Collections.unmodifiableList(causes);
  }

Gets a {@code Throwable} cause chain as a list. The first entry in the list will be {@code
throwable} followed by its cause hierarchy. Note that this is a snapshot of the cause chain and
will not reflect any subsequent changes to the cause chain.

Here's an example of how it can be used to find specific types of exceptions in the cause
chain:

Iterables.filter(Throwables.getCausalChain(e), IOException.class));

@param throwable the non-null {@code Throwable} to extract causes from
@return an unmodifiable list containing the cause chain starting with {@code throwable}
@throws IllegalArgumentException if there is a loop in the causal chain

Gets a { @code Throwable } cause chain as a list . The first entry in the list will be { @code throwable } followed by its cause hierarchy . Note that this is a snapshot of the cause chain and will not reflect any subsequent changes to the cause chain .


@Beta
  @GwtIncompatible // Class.cast(Object)
  public static <X extends Throwable> X getCauseAs(
      Throwable throwable, Class<X> expectedCauseType) {
    try {
      return expectedCauseType.cast(throwable.getCause());
    } catch (ClassCastException e) {
      e.initCause(throwable);
      throw e;
    }
  }

@
Beta
@
GwtIncompatible
// Class.cast(Object)
public
static
<
X
extends
Throwable
>
X
getCauseAs
(
Throwable
throwable
,
Class
<
X
>
expectedCauseType
)
{
try
{
return
expectedCauseType
.
cast
(
throwable
.
getCause
(
)
)
;
}
catch
(
ClassCastException
e
)
{
e
.
initCause
(
throwable
)
;
throw
e
;
}
}

Returns {@code throwable}'s cause, cast to {@code expectedCauseType}.

<p>Prefer this method instead of manually casting an exception's cause. For example, {@code
(IOException) e.getCause()} throws a {@link ClassCastException} that discards the original
exception {@code e} if the cause is not an {@link IOException}, but {@code
Throwables.getCauseAs(e, IOException.class)} keeps {@code e} as the {@link
ClassCastException}'s cause.

@throws ClassCastException if the cause cannot be cast to the expected type. The {@code
ClassCastException}'s cause is {@code throwable}.
@since 22.0

Returns { @code throwable } s cause cast to { @code expectedCauseType } .


@Beta
  @GwtIncompatible // lazyStackTraceIsLazy, jlaStackTrace
  // TODO(cpovirk): Consider making this available under GWT (slow implementation only).
  public static List<StackTraceElement> lazyStackTrace(Throwable throwable) {
    return lazyStackTraceIsLazy()
        ? jlaStackTrace(throwable)
        : unmodifiableList(asList(throwable.getStackTrace()));
  }

TODO(cpovirk): Say something about the possibility that List access could fail at runtime?

TODO ( cpovirk ) : Say something about the possibility that List access could fail at runtime?


public static Stats of(Iterable<? extends Number> values) {
    StatsAccumulator accumulator = new StatsAccumulator();
    accumulator.addAll(values);
    return accumulator.snapshot();
  }

public static Stats of ( Iterable < ? extends Number > values ) { StatsAccumulator accumulator = new StatsAccumulator ( ) ; accumulator . addAll ( values ) ; return accumulator . snapshot ( ) ; }

Returns statistics over a dataset containing the given values.

@param values a series of values, which will be converted to {@code double} values (this may
cause loss of precision)

Returns statistics over a dataset containing the given values .


public static Stats of(int... values) {
    StatsAccumulator acummulator = new StatsAccumulator();
    acummulator.addAll(values);
    return acummulator.snapshot();
  }

public static Stats of ( int ... values ) { StatsAccumulator acummulator = new StatsAccumulator ( ) ; acummulator . addAll ( values ) ; return acummulator . snapshot ( ) ; }

Returns statistics over a dataset containing the given values.

@param values a series of values


public double populationVariance() {
    checkState(count > 0);
    if (isNaN(sumOfSquaresOfDeltas)) {
      return NaN;
    }
    if (count == 1) {
      return 0.0;
    }
    return ensureNonNegative(sumOfSquaresOfDeltas) / count();
  }

public double populationVariance ( ) { checkState ( count > 0 ) ; if ( isNaN ( sumOfSquaresOfDeltas ) ) { return NaN ; } if ( count == 1 ) { return 0.0 ; } return ensureNonNegative ( sumOfSquaresOfDeltas ) / count ( ) ; }

Returns the population
variance of the values. The count must be non-zero.

This is guaranteed to return zero if the dataset contains only exactly one finite value. It
is not guaranteed to return zero when the dataset consists of the same value multiple times,
due to numerical errors. However, it is guaranteed never to return a negative result.

Non-finite values

If the dataset contains any non-finite values ({@link Double#POSITIVE_INFINITY}, {@link
Double#NEGATIVE_INFINITY}, or {@link Double#NaN}) then the result is {@link Double#NaN}.

@throws IllegalStateException if the dataset is empty

Returns the <a href = http : // en . wikipedia . org / wiki / Variance#Population_variance > population variance< / a > of the values . The count must be non - zero .


public static double meanOf(Iterator<? extends Number> values) {
    checkArgument(values.hasNext());
    long count = 1;
    double mean = values.next().doubleValue();
    while (values.hasNext()) {
      double value = values.next().doubleValue();
      count++;
      if (isFinite(value) && isFinite(mean)) {
        // Art of Computer Programming vol. 2, Knuth, 4.2.2, (15)
        mean += (value - mean) / count;
      } else {
        mean = calculateNewMeanNonFinite(mean, value);
      }
    }
    return mean;
  }

Returns the arithmetic mean of the
values. The count must be non-zero.

The definition of the mean is the same as {@link Stats#mean}.

@param values a series of values, which will be converted to {@code double} values (this may
cause loss of precision)
@throws IllegalArgumentException if the dataset is empty

Returns the <a href = http : // en . wikipedia . org / wiki / Arithmetic_mean > arithmetic mean< / a > of the values . The count must be non - zero .


public static double meanOf(long... values) {
    checkArgument(values.length > 0);
    double mean = values[0];
    for (int index = 1; index < values.length; index++) {
      double value = values[index];
      if (isFinite(value) && isFinite(mean)) {
        // Art of Computer Programming vol. 2, Knuth, 4.2.2, (15)
        mean += (value - mean) / (index + 1);
      } else {
        mean = calculateNewMeanNonFinite(mean, value);
      }
    }
    return mean;
  }

Returns the arithmetic mean of the
values. The count must be non-zero.

The definition of the mean is the same as {@link Stats#mean}.

@param values a series of values, which will be converted to {@code double} values (this may
cause loss of precision for longs of magnitude over 2^53 (slightly over 9e15))
@throws IllegalArgumentException if the dataset is empty


public byte[] toByteArray() {
    ByteBuffer buff = ByteBuffer.allocate(BYTES).order(ByteOrder.LITTLE_ENDIAN);
    writeTo(buff);
    return buff.array();
  }

public byte [ ] toByteArray ( ) { ByteBuffer buff = ByteBuffer . allocate ( BYTES ) . order ( ByteOrder . LITTLE_ENDIAN ) ; writeTo ( buff ) ; return buff . array ( ) ; }

Gets a byte array representation of this instance.

Note: No guarantees are made regarding stability of the representation between
versions.

Gets a byte array representation of this instance .


void writeTo(ByteBuffer buffer) {
    checkNotNull(buffer);
    checkArgument(
        buffer.remaining() >= BYTES,
        "Expected at least Stats.BYTES = %s remaining , got %s",
        BYTES,
        buffer.remaining());
    buffer
        .putLong(count)
        .putDouble(mean)
        .putDouble(sumOfSquaresOfDeltas)
        .putDouble(min)
        .putDouble(max);
  }

Writes to the given {@link ByteBuffer} a byte representation of this instance.

Note: No guarantees are made regarding stability of the representation between
versions.

@param buffer A {@link ByteBuffer} with at least BYTES {@link ByteBuffer#remaining}, ordered as
{@link ByteOrder#LITTLE_ENDIAN}, to which a BYTES-long byte representation of this instance
is written. In the process increases the position of {@link ByteBuffer} by BYTES.

Writes to the given { @link ByteBuffer } a byte representation of this instance .


public static Stats fromByteArray(byte[] byteArray) {
    checkNotNull(byteArray);
    checkArgument(
        byteArray.length == BYTES,
        "Expected Stats.BYTES = %s remaining , got %s",
        BYTES,
        byteArray.length);
    return readFrom(ByteBuffer.wrap(byteArray).order(ByteOrder.LITTLE_ENDIAN));
  }

Creates a Stats instance from the given byte representation which was obtained by {@link
#toByteArray}.

Note: No guarantees are made regarding stability of the representation between
versions.

Creates a Stats instance from the given byte representation which was obtained by { @link #toByteArray } .


static Stats readFrom(ByteBuffer buffer) {
    checkNotNull(buffer);
    checkArgument(
        buffer.remaining() >= BYTES,
        "Expected at least Stats.BYTES = %s remaining , got %s",
        BYTES,
        buffer.remaining());
    return new Stats(
        buffer.getLong(),
        buffer.getDouble(),
        buffer.getDouble(),
        buffer.getDouble(),
        buffer.getDouble());
  }

Creates a Stats instance from the byte representation read from the given {@link ByteBuffer}.

Note: No guarantees are made regarding stability of the representation between
versions.

@param buffer A {@link ByteBuffer} with at least BYTES {@link ByteBuffer#remaining}, ordered as
{@link ByteOrder#LITTLE_ENDIAN}, from which a BYTES-long byte representation of this
instance is read. In the process increases the position of {@link ByteBuffer} by BYTES.

Creates a Stats instance from the byte representation read from the given { @link ByteBuffer } .


public final void set(int i, double newValue) {
    long next = doubleToRawLongBits(newValue);
    longs.set(i, next);
  }

public final void set ( int i , double newValue ) { long next = doubleToRawLongBits ( newValue ) ; longs . set ( i , next ) ; }

Sets the element at position {@code i} to the given value.

@param i the index
@param newValue the new value

Sets the element at position { @code i } to the given value .


public final void lazySet(int i, double newValue) {
    long next = doubleToRawLongBits(newValue);
    longs.lazySet(i, next);
  }

public final void lazySet ( int i , double newValue ) { long next = doubleToRawLongBits ( newValue ) ; longs . lazySet ( i , next ) ; }

Eventually sets the element at position {@code i} to the given value.

@param i the index
@param newValue the new value

Eventually sets the element at position { @code i } to the given value .


public final double getAndSet(int i, double newValue) {
    long next = doubleToRawLongBits(newValue);
    return longBitsToDouble(longs.getAndSet(i, next));
  }

public final double getAndSet ( int i , double newValue ) { long next = doubleToRawLongBits ( newValue ) ; return longBitsToDouble ( longs . getAndSet ( i , next ) ) ; }

Atomically sets the element at position {@code i} to the given value and returns the old value.

@param i the index
@param newValue the new value
@return the previous value

Atomically sets the element at position { @code i } to the given value and returns the old value .


public final boolean compareAndSet(int i, double expect, double update) {
    return longs.compareAndSet(i, doubleToRawLongBits(expect), doubleToRawLongBits(update));
  }

public final boolean compareAndSet ( int i , double expect , double update ) { return longs . compareAndSet ( i , doubleToRawLongBits ( expect ) , doubleToRawLongBits ( update ) ) ; }

Atomically sets the element at position {@code i} to the given updated value if the current
value is bitwise equal to the expected value.

@param i the index
@param expect the expected value
@param update the new value
@return true if successful. False return indicates that the actual value was not equal to the
expected value.

Atomically sets the element at position { @code i } to the given updated value if the current value is <a href = #bitEquals > bitwise equal< / a > to the expected value .


public final boolean weakCompareAndSet(int i, double expect, double update) {
    return longs.weakCompareAndSet(i, doubleToRawLongBits(expect), doubleToRawLongBits(update));
  }

public final boolean weakCompareAndSet ( int i , double expect , double update ) { return longs . weakCompareAndSet ( i , doubleToRawLongBits ( expect ) , doubleToRawLongBits ( update ) ) ; }

Atomically sets the element at position {@code i} to the given updated value if the current
value is bitwise equal to the expected value.

May
fail spuriously and does not provide ordering guarantees, so is only rarely an appropriate
alternative to {@code compareAndSet}.

@param i the index
@param expect the expected value
@param update the new value
@return true if successful


@CanIgnoreReturnValue
  public final double getAndAdd(int i, double delta) {
    while (true) {
      long current = longs.get(i);
      double currentVal = longBitsToDouble(current);
      double nextVal = currentVal + delta;
      long next = doubleToRawLongBits(nextVal);
      if (longs.compareAndSet(i, current, next)) {
        return currentVal;
      }
    }
  }

@ CanIgnoreReturnValue public final double getAndAdd ( int i , double delta ) { while ( true ) { long current = longs . get ( i ) ; double currentVal = longBitsToDouble ( current ) ; double nextVal = currentVal + delta ; long next = doubleToRawLongBits ( nextVal ) ; if ( longs . compareAndSet ( i , current , next ) ) { return currentVal ; } } }

Atomically adds the given value to the element at index {@code i}.

@param i the index
@param delta the value to add
@return the previous value

Atomically adds the given value to the element at index { @code i } .


private void writeObject(java.io.ObjectOutputStream s) throws java.io.IOException {
    s.defaultWriteObject();

    // Write out array length
    int length = length();
    s.writeInt(length);

    // Write out all elements in the proper order.
    for (int i = 0; i < length; i++) {
      s.writeDouble(get(i));
    }
  }

Saves the state to a stream (that is, serializes it).

@serialData The length of the array is emitted (int), followed by all of its elements (each a
{@code double}) in the proper order.

Saves the state to a stream ( that is serializes it ) .


private void readObject(java.io.ObjectInputStream s)
      throws java.io.IOException, ClassNotFoundException {
    s.defaultReadObject();

    int length = s.readInt();
    ImmutableLongArray.Builder builder = ImmutableLongArray.builder();
    for (int i = 0; i < length; i++) {
      builder.add(doubleToRawLongBits(s.readDouble()));
    }
    this.longs = new AtomicLongArray(builder.build().toArray());
  }

private void readObject ( java . io . ObjectInputStream s ) throws java . io . IOException , ClassNotFoundException { s . defaultReadObject ( ) ; int length = s . readInt ( ) ; ImmutableLongArray . Builder builder = ImmutableLongArray . builder ( ) ; for ( int i = 0 ; i < length ; i ++ ) { builder . add ( doubleToRawLongBits ( s . readDouble ( ) ) ) ; } this . longs = new AtomicLongArray ( builder . build ( ) . toArray ( ) ) ; }

Reconstitutes the instance from a stream (that is, deserializes it).

Reconstitutes the instance from a stream ( that is deserializes it ) .


public static <N> EndpointPair<N> ordered(N source, N target) {
    return new Ordered<N>(source, target);
  }

public static < N > EndpointPair < N > ordered ( N source , N target ) { return new Ordered < N > ( source , target ) ; }

Returns an {@link EndpointPair} representing the endpoints of a directed edge.