001/*
002 * Copyright (C) 2007 The Guava Authors
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 * http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017package com.google.common.collect;
018
019import static com.google.common.base.Preconditions.checkNotNull;
020import static com.google.common.collect.CollectPreconditions.checkNonnegative;
021import static com.google.common.collect.CollectPreconditions.checkRemove;
022import static com.google.common.collect.NullnessCasts.uncheckedCastNullableTToT;
023import static java.util.Objects.requireNonNull;
024
025import com.google.common.annotations.GwtCompatible;
026import com.google.common.annotations.GwtIncompatible;
027import com.google.common.annotations.J2ktIncompatible;
028import com.google.common.base.Function;
029import com.google.common.base.Predicate;
030import com.google.common.base.Predicates;
031import com.google.common.base.Supplier;
032import com.google.common.collect.Maps.EntryTransformer;
033import com.google.errorprone.annotations.CanIgnoreReturnValue;
034import com.google.errorprone.annotations.InlineMe;
035import com.google.errorprone.annotations.concurrent.LazyInit;
036import com.google.j2objc.annotations.Weak;
037import com.google.j2objc.annotations.WeakOuter;
038import java.io.IOException;
039import java.io.ObjectInputStream;
040import java.io.ObjectOutputStream;
041import java.io.Serializable;
042import java.util.AbstractCollection;
043import java.util.Collection;
044import java.util.Collections;
045import java.util.Comparator;
046import java.util.HashSet;
047import java.util.Iterator;
048import java.util.List;
049import java.util.Map;
050import java.util.Map.Entry;
051import java.util.NavigableSet;
052import java.util.NoSuchElementException;
053import java.util.Set;
054import java.util.SortedSet;
055import java.util.stream.Collector;
056import java.util.stream.Stream;
057import org.jspecify.annotations.Nullable;
058
059/**
060 * Provides static methods acting on or generating a {@code Multimap}.
061 *
062 * <p>See the Guava User Guide article on <a href=
063 * "https://github.com/google/guava/wiki/CollectionUtilitiesExplained#multimaps">{@code
064 * Multimaps}</a>.
065 *
066 * @author Jared Levy
067 * @author Robert Konigsberg
068 * @author Mike Bostock
069 * @author Louis Wasserman
070 * @since 2.0
071 */
072@GwtCompatible(emulated = true)
073public final class Multimaps {
074  private Multimaps() {}
075
076  /**
077   * Returns a {@code Collector} accumulating entries into a {@code Multimap} generated from the
078   * specified supplier. The keys and values of the entries are the result of applying the provided
079   * mapping functions to the input elements, accumulated in the encounter order of the stream.
080   *
081   * <p>Example:
082   *
083   * <pre>{@code
084   * static final ListMultimap<Character, String> FIRST_LETTER_MULTIMAP =
085   *     Stream.of("banana", "apple", "carrot", "asparagus", "cherry")
086   *         .collect(
087   *             toMultimap(
088   *                  str -> str.charAt(0),
089   *                  str -> str.substring(1),
090   *                  MultimapBuilder.treeKeys().arrayListValues()::build));
091   *
092   * // is equivalent to
093   *
094   * static final ListMultimap<Character, String> FIRST_LETTER_MULTIMAP;
095   *
096   * static {
097   *     FIRST_LETTER_MULTIMAP = MultimapBuilder.treeKeys().arrayListValues().build();
098   *     FIRST_LETTER_MULTIMAP.put('b', "anana");
099   *     FIRST_LETTER_MULTIMAP.put('a', "pple");
100   *     FIRST_LETTER_MULTIMAP.put('a', "sparagus");
101   *     FIRST_LETTER_MULTIMAP.put('c', "arrot");
102   *     FIRST_LETTER_MULTIMAP.put('c', "herry");
103   * }
104   * }</pre>
105   *
106   * <p>To collect to an {@link ImmutableMultimap}, use either {@link
107   * ImmutableSetMultimap#toImmutableSetMultimap} or {@link
108   * ImmutableListMultimap#toImmutableListMultimap}.
109   *
110   * @since 33.2.0 (available since 21.0 in guava-jre)
111   */
112  @SuppressWarnings("Java7ApiChecker")
113  @IgnoreJRERequirement // Users will use this only if they're already using streams.
114  public static <
115          T extends @Nullable Object,
116          K extends @Nullable Object,
117          V extends @Nullable Object,
118          M extends Multimap<K, V>>
119      Collector<T, ?, M> toMultimap(
120          java.util.function.Function<? super T, ? extends K> keyFunction,
121          java.util.function.Function<? super T, ? extends V> valueFunction,
122          java.util.function.Supplier<M> multimapSupplier) {
123    return CollectCollectors.<T, K, V, M>toMultimap(keyFunction, valueFunction, multimapSupplier);
124  }
125
126  /**
127   * Returns a {@code Collector} accumulating entries into a {@code Multimap} generated from the
128   * specified supplier. Each input element is mapped to a key and a stream of values, each of which
129   * are put into the resulting {@code Multimap}, in the encounter order of the stream and the
130   * encounter order of the streams of values.
131   *
132   * <p>Example:
133   *
134   * <pre>{@code
135   * static final ListMultimap<Character, Character> FIRST_LETTER_MULTIMAP =
136   *     Stream.of("banana", "apple", "carrot", "asparagus", "cherry")
137   *         .collect(
138   *             flatteningToMultimap(
139   *                  str -> str.charAt(0),
140   *                  str -> str.substring(1).chars().mapToObj(c -> (char) c),
141   *                  MultimapBuilder.linkedHashKeys().arrayListValues()::build));
142   *
143   * // is equivalent to
144   *
145   * static final ListMultimap<Character, Character> FIRST_LETTER_MULTIMAP;
146   *
147   * static {
148   *     FIRST_LETTER_MULTIMAP = MultimapBuilder.linkedHashKeys().arrayListValues().build();
149   *     FIRST_LETTER_MULTIMAP.putAll('b', Arrays.asList('a', 'n', 'a', 'n', 'a'));
150   *     FIRST_LETTER_MULTIMAP.putAll('a', Arrays.asList('p', 'p', 'l', 'e'));
151   *     FIRST_LETTER_MULTIMAP.putAll('c', Arrays.asList('a', 'r', 'r', 'o', 't'));
152   *     FIRST_LETTER_MULTIMAP.putAll('a', Arrays.asList('s', 'p', 'a', 'r', 'a', 'g', 'u', 's'));
153   *     FIRST_LETTER_MULTIMAP.putAll('c', Arrays.asList('h', 'e', 'r', 'r', 'y'));
154   * }
155   * }</pre>
156   *
157   * @since 33.2.0 (available since 21.0 in guava-jre)
158   */
159  @SuppressWarnings("Java7ApiChecker")
160  @IgnoreJRERequirement // Users will use this only if they're already using streams.
161  public static <
162          T extends @Nullable Object,
163          K extends @Nullable Object,
164          V extends @Nullable Object,
165          M extends Multimap<K, V>>
166      Collector<T, ?, M> flatteningToMultimap(
167          java.util.function.Function<? super T, ? extends K> keyFunction,
168          java.util.function.Function<? super T, ? extends Stream<? extends V>> valueFunction,
169          java.util.function.Supplier<M> multimapSupplier) {
170    return CollectCollectors.<T, K, V, M>flatteningToMultimap(
171        keyFunction, valueFunction, multimapSupplier);
172  }
173
174  /**
175   * Creates a new {@code Multimap} backed by {@code map}, whose internal value collections are
176   * generated by {@code factory}.
177   *
178   * <p><b>Warning: do not use</b> this method when the collections returned by {@code factory}
179   * implement either {@link List} or {@code Set}! Use the more specific method {@link
180   * #newListMultimap}, {@link #newSetMultimap} or {@link #newSortedSetMultimap} instead, to avoid
181   * very surprising behavior from {@link Multimap#equals}.
182   *
183   * <p>The {@code factory}-generated and {@code map} classes determine the multimap iteration
184   * order. They also specify the behavior of the {@code equals}, {@code hashCode}, and {@code
185   * toString} methods for the multimap and its returned views. However, the multimap's {@code get}
186   * method returns instances of a different class than {@code factory.get()} does.
187   *
188   * <p>The multimap is serializable if {@code map}, {@code factory}, the collections generated by
189   * {@code factory}, and the multimap contents are all serializable.
190   *
191   * <p>The multimap is not threadsafe when any concurrent operations update the multimap, even if
192   * {@code map} and the instances generated by {@code factory} are. Concurrent read operations will
193   * work correctly. To allow concurrent update operations, wrap the multimap with a call to {@link
194   * #synchronizedMultimap}.
195   *
196   * <p>Call this method only when the simpler methods {@link ArrayListMultimap#create()}, {@link
197   * HashMultimap#create()}, {@link LinkedHashMultimap#create()}, {@link
198   * LinkedListMultimap#create()}, {@link TreeMultimap#create()}, and {@link
199   * TreeMultimap#create(Comparator, Comparator)} won't suffice.
200   *
201   * <p>Note: the multimap assumes complete ownership over of {@code map} and the collections
202   * returned by {@code factory}. Those objects should not be manually updated and they should not
203   * use soft, weak, or phantom references.
204   *
205   * @param map place to store the mapping from each key to its corresponding values
206   * @param factory supplier of new, empty collections that will each hold all values for a given
207   *     key
208   * @throws IllegalArgumentException if {@code map} is not empty
209   */
210  public static <K extends @Nullable Object, V extends @Nullable Object> Multimap<K, V> newMultimap(
211      Map<K, Collection<V>> map, Supplier<? extends Collection<V>> factory) {
212    return new CustomMultimap<>(map, factory);
213  }
214
215  private static class CustomMultimap<K extends @Nullable Object, V extends @Nullable Object>
216      extends AbstractMapBasedMultimap<K, V> {
217    transient Supplier<? extends Collection<V>> factory;
218
219    CustomMultimap(Map<K, Collection<V>> map, Supplier<? extends Collection<V>> factory) {
220      super(map);
221      this.factory = checkNotNull(factory);
222    }
223
224    @Override
225    Set<K> createKeySet() {
226      return createMaybeNavigableKeySet();
227    }
228
229    @Override
230    Map<K, Collection<V>> createAsMap() {
231      return createMaybeNavigableAsMap();
232    }
233
234    @Override
235    protected Collection<V> createCollection() {
236      return factory.get();
237    }
238
239    @Override
240    <E extends @Nullable Object> Collection<E> unmodifiableCollectionSubclass(
241        Collection<E> collection) {
242      if (collection instanceof NavigableSet) {
243        return Sets.unmodifiableNavigableSet((NavigableSet<E>) collection);
244      } else if (collection instanceof SortedSet) {
245        return Collections.unmodifiableSortedSet((SortedSet<E>) collection);
246      } else if (collection instanceof Set) {
247        return Collections.unmodifiableSet((Set<E>) collection);
248      } else if (collection instanceof List) {
249        return Collections.unmodifiableList((List<E>) collection);
250      } else {
251        return Collections.unmodifiableCollection(collection);
252      }
253    }
254
255    @Override
256    Collection<V> wrapCollection(@ParametricNullness K key, Collection<V> collection) {
257      if (collection instanceof List) {
258        return wrapList(key, (List<V>) collection, null);
259      } else if (collection instanceof NavigableSet) {
260        return new WrappedNavigableSet(key, (NavigableSet<V>) collection, null);
261      } else if (collection instanceof SortedSet) {
262        return new WrappedSortedSet(key, (SortedSet<V>) collection, null);
263      } else if (collection instanceof Set) {
264        return new WrappedSet(key, (Set<V>) collection);
265      } else {
266        return new WrappedCollection(key, collection, null);
267      }
268    }
269
270    // can't use Serialization writeMultimap and populateMultimap methods since
271    // there's no way to generate the empty backing map.
272
273    /**
274     * @serialData the factory and the backing map
275     */
276    @GwtIncompatible // java.io.ObjectOutputStream
277    @J2ktIncompatible
278    private void writeObject(ObjectOutputStream stream) throws IOException {
279      stream.defaultWriteObject();
280      stream.writeObject(factory);
281      stream.writeObject(backingMap());
282    }
283
284    @GwtIncompatible // java.io.ObjectInputStream
285    @J2ktIncompatible
286    @SuppressWarnings("unchecked") // reading data stored by writeObject
287    private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
288      stream.defaultReadObject();
289      factory = (Supplier<? extends Collection<V>>) requireNonNull(stream.readObject());
290      Map<K, Collection<V>> map = (Map<K, Collection<V>>) requireNonNull(stream.readObject());
291      setMap(map);
292    }
293
294    @GwtIncompatible @J2ktIncompatible private static final long serialVersionUID = 0;
295  }
296
297  /**
298   * Creates a new {@code ListMultimap} that uses the provided map and factory. It can generate a
299   * multimap based on arbitrary {@link Map} and {@link List} classes.
300   *
301   * <p>The {@code factory}-generated and {@code map} classes determine the multimap iteration
302   * order. They also specify the behavior of the {@code equals}, {@code hashCode}, and {@code
303   * toString} methods for the multimap and its returned views. The multimap's {@code get}, {@code
304   * removeAll}, and {@code replaceValues} methods return {@code RandomAccess} lists if the factory
305   * does. However, the multimap's {@code get} method returns instances of a different class than
306   * does {@code factory.get()}.
307   *
308   * <p>The multimap is serializable if {@code map}, {@code factory}, the lists generated by {@code
309   * factory}, and the multimap contents are all serializable.
310   *
311   * <p>The multimap is not threadsafe when any concurrent operations update the multimap, even if
312   * {@code map} and the instances generated by {@code factory} are. Concurrent read operations will
313   * work correctly. To allow concurrent update operations, wrap the multimap with a call to {@link
314   * #synchronizedListMultimap}.
315   *
316   * <p>Call this method only when the simpler methods {@link ArrayListMultimap#create()} and {@link
317   * LinkedListMultimap#create()} won't suffice.
318   *
319   * <p>Note: the multimap assumes complete ownership over of {@code map} and the lists returned by
320   * {@code factory}. Those objects should not be manually updated, they should be empty when
321   * provided, and they should not use soft, weak, or phantom references.
322   *
323   * @param map place to store the mapping from each key to its corresponding values
324   * @param factory supplier of new, empty lists that will each hold all values for a given key
325   * @throws IllegalArgumentException if {@code map} is not empty
326   */
327  public static <K extends @Nullable Object, V extends @Nullable Object>
328      ListMultimap<K, V> newListMultimap(
329          Map<K, Collection<V>> map, Supplier<? extends List<V>> factory) {
330    return new CustomListMultimap<>(map, factory);
331  }
332
333  private static class CustomListMultimap<K extends @Nullable Object, V extends @Nullable Object>
334      extends AbstractListMultimap<K, V> {
335    transient Supplier<? extends List<V>> factory;
336
337    CustomListMultimap(Map<K, Collection<V>> map, Supplier<? extends List<V>> factory) {
338      super(map);
339      this.factory = checkNotNull(factory);
340    }
341
342    @Override
343    Set<K> createKeySet() {
344      return createMaybeNavigableKeySet();
345    }
346
347    @Override
348    Map<K, Collection<V>> createAsMap() {
349      return createMaybeNavigableAsMap();
350    }
351
352    @Override
353    protected List<V> createCollection() {
354      return factory.get();
355    }
356
357    /**
358     * @serialData the factory and the backing map
359     */
360    @GwtIncompatible // java.io.ObjectOutputStream
361    @J2ktIncompatible
362    private void writeObject(ObjectOutputStream stream) throws IOException {
363      stream.defaultWriteObject();
364      stream.writeObject(factory);
365      stream.writeObject(backingMap());
366    }
367
368    @GwtIncompatible // java.io.ObjectInputStream
369    @J2ktIncompatible
370    @SuppressWarnings("unchecked") // reading data stored by writeObject
371    private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
372      stream.defaultReadObject();
373      factory = (Supplier<? extends List<V>>) requireNonNull(stream.readObject());
374      Map<K, Collection<V>> map = (Map<K, Collection<V>>) requireNonNull(stream.readObject());
375      setMap(map);
376    }
377
378    @GwtIncompatible @J2ktIncompatible private static final long serialVersionUID = 0;
379  }
380
381  /**
382   * Creates a new {@code SetMultimap} that uses the provided map and factory. It can generate a
383   * multimap based on arbitrary {@link Map} and {@link Set} classes.
384   *
385   * <p>The {@code factory}-generated and {@code map} classes determine the multimap iteration
386   * order. They also specify the behavior of the {@code equals}, {@code hashCode}, and {@code
387   * toString} methods for the multimap and its returned views. However, the multimap's {@code get}
388   * method returns instances of a different class than {@code factory.get()} does.
389   *
390   * <p>The multimap is serializable if {@code map}, {@code factory}, the sets generated by {@code
391   * factory}, and the multimap contents are all serializable.
392   *
393   * <p>The multimap is not threadsafe when any concurrent operations update the multimap, even if
394   * {@code map} and the instances generated by {@code factory} are. Concurrent read operations will
395   * work correctly. To allow concurrent update operations, wrap the multimap with a call to {@link
396   * #synchronizedSetMultimap}.
397   *
398   * <p>Call this method only when the simpler methods {@link HashMultimap#create()}, {@link
399   * LinkedHashMultimap#create()}, {@link TreeMultimap#create()}, and {@link
400   * TreeMultimap#create(Comparator, Comparator)} won't suffice.
401   *
402   * <p>Note: the multimap assumes complete ownership over of {@code map} and the sets returned by
403   * {@code factory}. Those objects should not be manually updated and they should not use soft,
404   * weak, or phantom references.
405   *
406   * @param map place to store the mapping from each key to its corresponding values
407   * @param factory supplier of new, empty sets that will each hold all values for a given key
408   * @throws IllegalArgumentException if {@code map} is not empty
409   */
410  public static <K extends @Nullable Object, V extends @Nullable Object>
411      SetMultimap<K, V> newSetMultimap(
412          Map<K, Collection<V>> map, Supplier<? extends Set<V>> factory) {
413    return new CustomSetMultimap<>(map, factory);
414  }
415
416  private static class CustomSetMultimap<K extends @Nullable Object, V extends @Nullable Object>
417      extends AbstractSetMultimap<K, V> {
418    transient Supplier<? extends Set<V>> factory;
419
420    CustomSetMultimap(Map<K, Collection<V>> map, Supplier<? extends Set<V>> factory) {
421      super(map);
422      this.factory = checkNotNull(factory);
423    }
424
425    @Override
426    Set<K> createKeySet() {
427      return createMaybeNavigableKeySet();
428    }
429
430    @Override
431    Map<K, Collection<V>> createAsMap() {
432      return createMaybeNavigableAsMap();
433    }
434
435    @Override
436    protected Set<V> createCollection() {
437      return factory.get();
438    }
439
440    @Override
441    <E extends @Nullable Object> Collection<E> unmodifiableCollectionSubclass(
442        Collection<E> collection) {
443      if (collection instanceof NavigableSet) {
444        return Sets.unmodifiableNavigableSet((NavigableSet<E>) collection);
445      } else if (collection instanceof SortedSet) {
446        return Collections.unmodifiableSortedSet((SortedSet<E>) collection);
447      } else {
448        return Collections.unmodifiableSet((Set<E>) collection);
449      }
450    }
451
452    @Override
453    Collection<V> wrapCollection(@ParametricNullness K key, Collection<V> collection) {
454      if (collection instanceof NavigableSet) {
455        return new WrappedNavigableSet(key, (NavigableSet<V>) collection, null);
456      } else if (collection instanceof SortedSet) {
457        return new WrappedSortedSet(key, (SortedSet<V>) collection, null);
458      } else {
459        return new WrappedSet(key, (Set<V>) collection);
460      }
461    }
462
463    /**
464     * @serialData the factory and the backing map
465     */
466    @GwtIncompatible // java.io.ObjectOutputStream
467    @J2ktIncompatible
468    private void writeObject(ObjectOutputStream stream) throws IOException {
469      stream.defaultWriteObject();
470      stream.writeObject(factory);
471      stream.writeObject(backingMap());
472    }
473
474    @GwtIncompatible // java.io.ObjectInputStream
475    @J2ktIncompatible
476    @SuppressWarnings("unchecked") // reading data stored by writeObject
477    private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
478      stream.defaultReadObject();
479      factory = (Supplier<? extends Set<V>>) requireNonNull(stream.readObject());
480      Map<K, Collection<V>> map = (Map<K, Collection<V>>) requireNonNull(stream.readObject());
481      setMap(map);
482    }
483
484    @GwtIncompatible @J2ktIncompatible private static final long serialVersionUID = 0;
485  }
486
487  /**
488   * Creates a new {@code SortedSetMultimap} that uses the provided map and factory. It can generate
489   * a multimap based on arbitrary {@link Map} and {@link SortedSet} classes.
490   *
491   * <p>The {@code factory}-generated and {@code map} classes determine the multimap iteration
492   * order. They also specify the behavior of the {@code equals}, {@code hashCode}, and {@code
493   * toString} methods for the multimap and its returned views. However, the multimap's {@code get}
494   * method returns instances of a different class than {@code factory.get()} does.
495   *
496   * <p>The multimap is serializable if {@code map}, {@code factory}, the sets generated by {@code
497   * factory}, and the multimap contents are all serializable.
498   *
499   * <p>The multimap is not threadsafe when any concurrent operations update the multimap, even if
500   * {@code map} and the instances generated by {@code factory} are. Concurrent read operations will
501   * work correctly. To allow concurrent update operations, wrap the multimap with a call to {@link
502   * #synchronizedSortedSetMultimap}.
503   *
504   * <p>Call this method only when the simpler methods {@link TreeMultimap#create()} and {@link
505   * TreeMultimap#create(Comparator, Comparator)} won't suffice.
506   *
507   * <p>Note: the multimap assumes complete ownership over of {@code map} and the sets returned by
508   * {@code factory}. Those objects should not be manually updated and they should not use soft,
509   * weak, or phantom references.
510   *
511   * @param map place to store the mapping from each key to its corresponding values
512   * @param factory supplier of new, empty sorted sets that will each hold all values for a given
513   *     key
514   * @throws IllegalArgumentException if {@code map} is not empty
515   */
516  public static <K extends @Nullable Object, V extends @Nullable Object>
517      SortedSetMultimap<K, V> newSortedSetMultimap(
518          Map<K, Collection<V>> map, Supplier<? extends SortedSet<V>> factory) {
519    return new CustomSortedSetMultimap<>(map, factory);
520  }
521
522  private static class CustomSortedSetMultimap<
523          K extends @Nullable Object, V extends @Nullable Object>
524      extends AbstractSortedSetMultimap<K, V> {
525    transient Supplier<? extends SortedSet<V>> factory;
526    transient @Nullable Comparator<? super V> valueComparator;
527
528    CustomSortedSetMultimap(Map<K, Collection<V>> map, Supplier<? extends SortedSet<V>> factory) {
529      super(map);
530      this.factory = checkNotNull(factory);
531      valueComparator = factory.get().comparator();
532    }
533
534    @Override
535    Set<K> createKeySet() {
536      return createMaybeNavigableKeySet();
537    }
538
539    @Override
540    Map<K, Collection<V>> createAsMap() {
541      return createMaybeNavigableAsMap();
542    }
543
544    @Override
545    protected SortedSet<V> createCollection() {
546      return factory.get();
547    }
548
549    @Override
550    public @Nullable Comparator<? super V> valueComparator() {
551      return valueComparator;
552    }
553
554    /**
555     * @serialData the factory and the backing map
556     */
557    @GwtIncompatible // java.io.ObjectOutputStream
558    @J2ktIncompatible
559    private void writeObject(ObjectOutputStream stream) throws IOException {
560      stream.defaultWriteObject();
561      stream.writeObject(factory);
562      stream.writeObject(backingMap());
563    }
564
565    @GwtIncompatible // java.io.ObjectInputStream
566    @J2ktIncompatible
567    @SuppressWarnings("unchecked") // reading data stored by writeObject
568    private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
569      stream.defaultReadObject();
570      factory = (Supplier<? extends SortedSet<V>>) requireNonNull(stream.readObject());
571      valueComparator = factory.get().comparator();
572      Map<K, Collection<V>> map = (Map<K, Collection<V>>) requireNonNull(stream.readObject());
573      setMap(map);
574    }
575
576    @GwtIncompatible @J2ktIncompatible private static final long serialVersionUID = 0;
577  }
578
579  /**
580   * Copies each key-value mapping in {@code source} into {@code dest}, with its key and value
581   * reversed.
582   *
583   * <p>If {@code source} is an {@link ImmutableMultimap}, consider using {@link
584   * ImmutableMultimap#inverse} instead.
585   *
586   * @param source any multimap
587   * @param dest the multimap to copy into; usually empty
588   * @return {@code dest}
589   */
590  @CanIgnoreReturnValue
591  public static <K extends @Nullable Object, V extends @Nullable Object, M extends Multimap<K, V>>
592      M invertFrom(Multimap<? extends V, ? extends K> source, M dest) {
593    checkNotNull(dest);
594    for (Map.Entry<? extends V, ? extends K> entry : source.entries()) {
595      dest.put(entry.getValue(), entry.getKey());
596    }
597    return dest;
598  }
599
600  /**
601   * Returns a synchronized (thread-safe) multimap backed by the specified multimap. In order to
602   * guarantee serial access, it is critical that <b>all</b> access to the backing multimap is
603   * accomplished through the returned multimap.
604   *
605   * <p>It is imperative that the user manually synchronize on the returned multimap when accessing
606   * any of its collection views:
607   *
608   * <pre>{@code
609   * Multimap<K, V> multimap = Multimaps.synchronizedMultimap(
610   *     HashMultimap.<K, V>create());
611   * ...
612   * Collection<V> values = multimap.get(key);  // Needn't be in synchronized block
613   * ...
614   * synchronized (multimap) {  // Synchronizing on multimap, not values!
615   *   Iterator<V> i = values.iterator(); // Must be in synchronized block
616   *   while (i.hasNext()) {
617   *     foo(i.next());
618   *   }
619   * }
620   * }</pre>
621   *
622   * <p>Failure to follow this advice may result in non-deterministic behavior.
623   *
624   * <p>Note that the generated multimap's {@link Multimap#removeAll} and {@link
625   * Multimap#replaceValues} methods return collections that aren't synchronized.
626   *
627   * <p>The returned multimap will be serializable if the specified multimap is serializable.
628   *
629   * @param multimap the multimap to be wrapped in a synchronized view
630   * @return a synchronized view of the specified multimap
631   */
632  @J2ktIncompatible // Synchronized
633  public static <K extends @Nullable Object, V extends @Nullable Object>
634      Multimap<K, V> synchronizedMultimap(Multimap<K, V> multimap) {
635    return Synchronized.multimap(multimap, null);
636  }
637
638  /**
639   * Returns an unmodifiable view of the specified multimap. Query operations on the returned
640   * multimap "read through" to the specified multimap, and attempts to modify the returned
641   * multimap, either directly or through the multimap's views, result in an {@code
642   * UnsupportedOperationException}.
643   *
644   * <p>The returned multimap will be serializable if the specified multimap is serializable.
645   *
646   * @param delegate the multimap for which an unmodifiable view is to be returned
647   * @return an unmodifiable view of the specified multimap
648   */
649  public static <K extends @Nullable Object, V extends @Nullable Object>
650      Multimap<K, V> unmodifiableMultimap(Multimap<K, V> delegate) {
651    if (delegate instanceof UnmodifiableMultimap || delegate instanceof ImmutableMultimap) {
652      return delegate;
653    }
654    return new UnmodifiableMultimap<>(delegate);
655  }
656
657  /**
658   * Simply returns its argument.
659   *
660   * @deprecated no need to use this
661   * @since 10.0
662   */
663  @InlineMe(
664      replacement = "checkNotNull(delegate)",
665      staticImports = "com.google.common.base.Preconditions.checkNotNull")
666  @Deprecated
667  public static <K, V> Multimap<K, V> unmodifiableMultimap(ImmutableMultimap<K, V> delegate) {
668    return checkNotNull(delegate);
669  }
670
671  private static class UnmodifiableMultimap<K extends @Nullable Object, V extends @Nullable Object>
672      extends ForwardingMultimap<K, V> implements Serializable {
673    final Multimap<K, V> delegate;
674    @LazyInit transient @Nullable Collection<Entry<K, V>> entries;
675    @LazyInit transient @Nullable Multiset<K> keys;
676    @LazyInit transient @Nullable Set<K> keySet;
677    @LazyInit transient @Nullable Collection<V> values;
678    @LazyInit transient @Nullable Map<K, Collection<V>> map;
679
680    UnmodifiableMultimap(Multimap<K, V> delegate) {
681      this.delegate = checkNotNull(delegate);
682    }
683
684    @Override
685    protected Multimap<K, V> delegate() {
686      return delegate;
687    }
688
689    @Override
690    public void clear() {
691      throw new UnsupportedOperationException();
692    }
693
694    @Override
695    public Map<K, Collection<V>> asMap() {
696      Map<K, Collection<V>> result = map;
697      if (result == null) {
698        result =
699            map =
700                Collections.unmodifiableMap(
701                    Maps.transformValues(delegate.asMap(), Multimaps::unmodifiableValueCollection));
702      }
703      return result;
704    }
705
706    @Override
707    public Collection<Entry<K, V>> entries() {
708      Collection<Entry<K, V>> result = entries;
709      if (result == null) {
710        entries = result = unmodifiableEntries(delegate.entries());
711      }
712      return result;
713    }
714
715    @Override
716    public Collection<V> get(@ParametricNullness K key) {
717      return unmodifiableValueCollection(delegate.get(key));
718    }
719
720    @Override
721    public Multiset<K> keys() {
722      Multiset<K> result = keys;
723      if (result == null) {
724        keys = result = Multisets.unmodifiableMultiset(delegate.keys());
725      }
726      return result;
727    }
728
729    @Override
730    public Set<K> keySet() {
731      Set<K> result = keySet;
732      if (result == null) {
733        keySet = result = Collections.unmodifiableSet(delegate.keySet());
734      }
735      return result;
736    }
737
738    @Override
739    public boolean put(@ParametricNullness K key, @ParametricNullness V value) {
740      throw new UnsupportedOperationException();
741    }
742
743    @Override
744    public boolean putAll(@ParametricNullness K key, Iterable<? extends V> values) {
745      throw new UnsupportedOperationException();
746    }
747
748    @Override
749    public boolean putAll(Multimap<? extends K, ? extends V> multimap) {
750      throw new UnsupportedOperationException();
751    }
752
753    @Override
754    public boolean remove(@Nullable Object key, @Nullable Object value) {
755      throw new UnsupportedOperationException();
756    }
757
758    @Override
759    public Collection<V> removeAll(@Nullable Object key) {
760      throw new UnsupportedOperationException();
761    }
762
763    @Override
764    public Collection<V> replaceValues(@ParametricNullness K key, Iterable<? extends V> values) {
765      throw new UnsupportedOperationException();
766    }
767
768    @Override
769    public Collection<V> values() {
770      Collection<V> result = values;
771      if (result == null) {
772        values = result = Collections.unmodifiableCollection(delegate.values());
773      }
774      return result;
775    }
776
777    @GwtIncompatible @J2ktIncompatible private static final long serialVersionUID = 0;
778  }
779
780  private static class UnmodifiableListMultimap<
781          K extends @Nullable Object, V extends @Nullable Object>
782      extends UnmodifiableMultimap<K, V> implements ListMultimap<K, V> {
783    UnmodifiableListMultimap(ListMultimap<K, V> delegate) {
784      super(delegate);
785    }
786
787    @Override
788    public ListMultimap<K, V> delegate() {
789      return (ListMultimap<K, V>) super.delegate();
790    }
791
792    @Override
793    public List<V> get(@ParametricNullness K key) {
794      return Collections.unmodifiableList(delegate().get(key));
795    }
796
797    @Override
798    public List<V> removeAll(@Nullable Object key) {
799      throw new UnsupportedOperationException();
800    }
801
802    @Override
803    public List<V> replaceValues(@ParametricNullness K key, Iterable<? extends V> values) {
804      throw new UnsupportedOperationException();
805    }
806
807    @GwtIncompatible @J2ktIncompatible private static final long serialVersionUID = 0;
808  }
809
810  private static class UnmodifiableSetMultimap<
811          K extends @Nullable Object, V extends @Nullable Object>
812      extends UnmodifiableMultimap<K, V> implements SetMultimap<K, V> {
813    UnmodifiableSetMultimap(SetMultimap<K, V> delegate) {
814      super(delegate);
815    }
816
817    @Override
818    public SetMultimap<K, V> delegate() {
819      return (SetMultimap<K, V>) super.delegate();
820    }
821
822    @Override
823    public Set<V> get(@ParametricNullness K key) {
824      /*
825       * Note that this doesn't return a SortedSet when delegate is a
826       * SortedSetMultiset, unlike (SortedSet<V>) super.get().
827       */
828      return Collections.unmodifiableSet(delegate().get(key));
829    }
830
831    @Override
832    public Set<Map.Entry<K, V>> entries() {
833      return Maps.unmodifiableEntrySet(delegate().entries());
834    }
835
836    @Override
837    public Set<V> removeAll(@Nullable Object key) {
838      throw new UnsupportedOperationException();
839    }
840
841    @Override
842    public Set<V> replaceValues(@ParametricNullness K key, Iterable<? extends V> values) {
843      throw new UnsupportedOperationException();
844    }
845
846    @GwtIncompatible @J2ktIncompatible private static final long serialVersionUID = 0;
847  }
848
849  private static class UnmodifiableSortedSetMultimap<
850          K extends @Nullable Object, V extends @Nullable Object>
851      extends UnmodifiableSetMultimap<K, V> implements SortedSetMultimap<K, V> {
852    UnmodifiableSortedSetMultimap(SortedSetMultimap<K, V> delegate) {
853      super(delegate);
854    }
855
856    @Override
857    public SortedSetMultimap<K, V> delegate() {
858      return (SortedSetMultimap<K, V>) super.delegate();
859    }
860
861    @Override
862    public SortedSet<V> get(@ParametricNullness K key) {
863      return Collections.unmodifiableSortedSet(delegate().get(key));
864    }
865
866    @Override
867    public SortedSet<V> removeAll(@Nullable Object key) {
868      throw new UnsupportedOperationException();
869    }
870
871    @Override
872    public SortedSet<V> replaceValues(@ParametricNullness K key, Iterable<? extends V> values) {
873      throw new UnsupportedOperationException();
874    }
875
876    @Override
877    public @Nullable Comparator<? super V> valueComparator() {
878      return delegate().valueComparator();
879    }
880
881    @GwtIncompatible @J2ktIncompatible private static final long serialVersionUID = 0;
882  }
883
884  /**
885   * Returns a synchronized (thread-safe) {@code SetMultimap} backed by the specified multimap.
886   *
887   * <p>You must follow the warnings described in {@link #synchronizedMultimap}.
888   *
889   * <p>The returned multimap will be serializable if the specified multimap is serializable.
890   *
891   * @param multimap the multimap to be wrapped
892   * @return a synchronized view of the specified multimap
893   */
894  @J2ktIncompatible // Synchronized
895  public static <K extends @Nullable Object, V extends @Nullable Object>
896      SetMultimap<K, V> synchronizedSetMultimap(SetMultimap<K, V> multimap) {
897    return Synchronized.setMultimap(multimap, null);
898  }
899
900  /**
901   * Returns an unmodifiable view of the specified {@code SetMultimap}. Query operations on the
902   * returned multimap "read through" to the specified multimap, and attempts to modify the returned
903   * multimap, either directly or through the multimap's views, result in an {@code
904   * UnsupportedOperationException}.
905   *
906   * <p>The returned multimap will be serializable if the specified multimap is serializable.
907   *
908   * @param delegate the multimap for which an unmodifiable view is to be returned
909   * @return an unmodifiable view of the specified multimap
910   */
911  public static <K extends @Nullable Object, V extends @Nullable Object>
912      SetMultimap<K, V> unmodifiableSetMultimap(SetMultimap<K, V> delegate) {
913    if (delegate instanceof UnmodifiableSetMultimap || delegate instanceof ImmutableSetMultimap) {
914      return delegate;
915    }
916    return new UnmodifiableSetMultimap<>(delegate);
917  }
918
919  /**
920   * Simply returns its argument.
921   *
922   * @deprecated no need to use this
923   * @since 10.0
924   */
925  @InlineMe(
926      replacement = "checkNotNull(delegate)",
927      staticImports = "com.google.common.base.Preconditions.checkNotNull")
928  @Deprecated
929  public static <K, V> SetMultimap<K, V> unmodifiableSetMultimap(
930      ImmutableSetMultimap<K, V> delegate) {
931    return checkNotNull(delegate);
932  }
933
934  /**
935   * Returns a synchronized (thread-safe) {@code SortedSetMultimap} backed by the specified
936   * multimap.
937   *
938   * <p>You must follow the warnings described in {@link #synchronizedMultimap}.
939   *
940   * <p>The returned multimap will be serializable if the specified multimap is serializable.
941   *
942   * @param multimap the multimap to be wrapped
943   * @return a synchronized view of the specified multimap
944   */
945  @J2ktIncompatible // Synchronized
946  public static <K extends @Nullable Object, V extends @Nullable Object>
947      SortedSetMultimap<K, V> synchronizedSortedSetMultimap(SortedSetMultimap<K, V> multimap) {
948    return Synchronized.sortedSetMultimap(multimap, null);
949  }
950
951  /**
952   * Returns an unmodifiable view of the specified {@code SortedSetMultimap}. Query operations on
953   * the returned multimap "read through" to the specified multimap, and attempts to modify the
954   * returned multimap, either directly or through the multimap's views, result in an {@code
955   * UnsupportedOperationException}.
956   *
957   * <p>The returned multimap will be serializable if the specified multimap is serializable.
958   *
959   * @param delegate the multimap for which an unmodifiable view is to be returned
960   * @return an unmodifiable view of the specified multimap
961   */
962  public static <K extends @Nullable Object, V extends @Nullable Object>
963      SortedSetMultimap<K, V> unmodifiableSortedSetMultimap(SortedSetMultimap<K, V> delegate) {
964    if (delegate instanceof UnmodifiableSortedSetMultimap) {
965      return delegate;
966    }
967    return new UnmodifiableSortedSetMultimap<>(delegate);
968  }
969
970  /**
971   * Returns a synchronized (thread-safe) {@code ListMultimap} backed by the specified multimap.
972   *
973   * <p>You must follow the warnings described in {@link #synchronizedMultimap}.
974   *
975   * @param multimap the multimap to be wrapped
976   * @return a synchronized view of the specified multimap
977   */
978  @J2ktIncompatible // Synchronized
979  public static <K extends @Nullable Object, V extends @Nullable Object>
980      ListMultimap<K, V> synchronizedListMultimap(ListMultimap<K, V> multimap) {
981    return Synchronized.listMultimap(multimap, null);
982  }
983
984  /**
985   * Returns an unmodifiable view of the specified {@code ListMultimap}. Query operations on the
986   * returned multimap "read through" to the specified multimap, and attempts to modify the returned
987   * multimap, either directly or through the multimap's views, result in an {@code
988   * UnsupportedOperationException}.
989   *
990   * <p>The returned multimap will be serializable if the specified multimap is serializable.
991   *
992   * @param delegate the multimap for which an unmodifiable view is to be returned
993   * @return an unmodifiable view of the specified multimap
994   */
995  public static <K extends @Nullable Object, V extends @Nullable Object>
996      ListMultimap<K, V> unmodifiableListMultimap(ListMultimap<K, V> delegate) {
997    if (delegate instanceof UnmodifiableListMultimap || delegate instanceof ImmutableListMultimap) {
998      return delegate;
999    }
1000    return new UnmodifiableListMultimap<>(delegate);
1001  }
1002
1003  /**
1004   * Simply returns its argument.
1005   *
1006   * @deprecated no need to use this
1007   * @since 10.0
1008   */
1009  @InlineMe(
1010      replacement = "checkNotNull(delegate)",
1011      staticImports = "com.google.common.base.Preconditions.checkNotNull")
1012  @Deprecated
1013  public static <K, V> ListMultimap<K, V> unmodifiableListMultimap(
1014      ImmutableListMultimap<K, V> delegate) {
1015    return checkNotNull(delegate);
1016  }
1017
1018  /**
1019   * Returns an unmodifiable view of the specified collection, preserving the interface for
1020   * instances of {@code SortedSet}, {@code Set}, {@code List} and {@code Collection}, in that order
1021   * of preference.
1022   *
1023   * @param collection the collection for which to return an unmodifiable view
1024   * @return an unmodifiable view of the collection
1025   */
1026  private static <V extends @Nullable Object> Collection<V> unmodifiableValueCollection(
1027      Collection<V> collection) {
1028    if (collection instanceof SortedSet) {
1029      return Collections.unmodifiableSortedSet((SortedSet<V>) collection);
1030    } else if (collection instanceof Set) {
1031      return Collections.unmodifiableSet((Set<V>) collection);
1032    } else if (collection instanceof List) {
1033      return Collections.unmodifiableList((List<V>) collection);
1034    }
1035    return Collections.unmodifiableCollection(collection);
1036  }
1037
1038  /**
1039   * Returns an unmodifiable view of the specified collection of entries. The {@link Entry#setValue}
1040   * operation throws an {@link UnsupportedOperationException}. If the specified collection is a
1041   * {@code Set}, the returned collection is also a {@code Set}.
1042   *
1043   * @param entries the entries for which to return an unmodifiable view
1044   * @return an unmodifiable view of the entries
1045   */
1046  private static <K extends @Nullable Object, V extends @Nullable Object>
1047      Collection<Entry<K, V>> unmodifiableEntries(Collection<Entry<K, V>> entries) {
1048    if (entries instanceof Set) {
1049      return Maps.unmodifiableEntrySet((Set<Entry<K, V>>) entries);
1050    }
1051    return new Maps.UnmodifiableEntries<>(Collections.unmodifiableCollection(entries));
1052  }
1053
1054  /**
1055   * Returns {@link ListMultimap#asMap multimap.asMap()}, with its type corrected from {@code Map<K,
1056   * Collection<V>>} to {@code Map<K, List<V>>}.
1057   *
1058   * @since 15.0
1059   */
1060  @SuppressWarnings("unchecked")
1061  // safe by specification of ListMultimap.asMap()
1062  public static <K extends @Nullable Object, V extends @Nullable Object> Map<K, List<V>> asMap(
1063      ListMultimap<K, V> multimap) {
1064    return (Map<K, List<V>>) (Map<K, ?>) multimap.asMap();
1065  }
1066
1067  /**
1068   * Returns {@link SetMultimap#asMap multimap.asMap()}, with its type corrected from {@code Map<K,
1069   * Collection<V>>} to {@code Map<K, Set<V>>}.
1070   *
1071   * @since 15.0
1072   */
1073  @SuppressWarnings("unchecked")
1074  // safe by specification of SetMultimap.asMap()
1075  public static <K extends @Nullable Object, V extends @Nullable Object> Map<K, Set<V>> asMap(
1076      SetMultimap<K, V> multimap) {
1077    return (Map<K, Set<V>>) (Map<K, ?>) multimap.asMap();
1078  }
1079
1080  /**
1081   * Returns {@link SortedSetMultimap#asMap multimap.asMap()}, with its type corrected from {@code
1082   * Map<K, Collection<V>>} to {@code Map<K, SortedSet<V>>}.
1083   *
1084   * @since 15.0
1085   */
1086  @SuppressWarnings("unchecked")
1087  // safe by specification of SortedSetMultimap.asMap()
1088  public static <K extends @Nullable Object, V extends @Nullable Object> Map<K, SortedSet<V>> asMap(
1089      SortedSetMultimap<K, V> multimap) {
1090    return (Map<K, SortedSet<V>>) (Map<K, ?>) multimap.asMap();
1091  }
1092
1093  /**
1094   * Returns {@link Multimap#asMap multimap.asMap()}. This is provided for parity with the other
1095   * more strongly-typed {@code asMap()} implementations.
1096   *
1097   * @since 15.0
1098   */
1099  public static <K extends @Nullable Object, V extends @Nullable Object>
1100      Map<K, Collection<V>> asMap(Multimap<K, V> multimap) {
1101    return multimap.asMap();
1102  }
1103
1104  /**
1105   * Returns a multimap view of the specified map. The multimap is backed by the map, so changes to
1106   * the map are reflected in the multimap, and vice versa. If the map is modified while an
1107   * iteration over one of the multimap's collection views is in progress (except through the
1108   * iterator's own {@code remove} operation, or through the {@code setValue} operation on a map
1109   * entry returned by the iterator), the results of the iteration are undefined.
1110   *
1111   * <p>The multimap supports mapping removal, which removes the corresponding mapping from the map.
1112   * It does not support any operations which might add mappings, such as {@code put}, {@code
1113   * putAll} or {@code replaceValues}.
1114   *
1115   * <p>The returned multimap will be serializable if the specified map is serializable.
1116   *
1117   * @param map the backing map for the returned multimap view
1118   */
1119  public static <K extends @Nullable Object, V extends @Nullable Object> SetMultimap<K, V> forMap(
1120      Map<K, V> map) {
1121    return new MapMultimap<>(map);
1122  }
1123
1124  /**
1125   * @see Multimaps#forMap
1126   */
1127  private static class MapMultimap<K extends @Nullable Object, V extends @Nullable Object>
1128      extends AbstractMultimap<K, V> implements SetMultimap<K, V>, Serializable {
1129    final Map<K, V> map;
1130
1131    MapMultimap(Map<K, V> map) {
1132      this.map = checkNotNull(map);
1133    }
1134
1135    @Override
1136    public int size() {
1137      return map.size();
1138    }
1139
1140    @Override
1141    public boolean containsKey(@Nullable Object key) {
1142      return map.containsKey(key);
1143    }
1144
1145    @Override
1146    public boolean containsValue(@Nullable Object value) {
1147      return map.containsValue(value);
1148    }
1149
1150    @Override
1151    public boolean containsEntry(@Nullable Object key, @Nullable Object value) {
1152      return map.entrySet().contains(Maps.immutableEntry(key, value));
1153    }
1154
1155    @Override
1156    public Set<V> get(@ParametricNullness K key) {
1157      return new Sets.ImprovedAbstractSet<V>() {
1158        @Override
1159        public Iterator<V> iterator() {
1160          return new Iterator<V>() {
1161            int i;
1162
1163            @Override
1164            public boolean hasNext() {
1165              return (i == 0) && map.containsKey(key);
1166            }
1167
1168            @Override
1169            @ParametricNullness
1170            public V next() {
1171              if (!hasNext()) {
1172                throw new NoSuchElementException();
1173              }
1174              i++;
1175              /*
1176               * The cast is safe because of the containsKey check in hasNext(). (That means it's
1177               * unsafe under concurrent modification, but all bets are off then, anyway.)
1178               */
1179              return uncheckedCastNullableTToT(map.get(key));
1180            }
1181
1182            @Override
1183            public void remove() {
1184              checkRemove(i == 1);
1185              i = -1;
1186              map.remove(key);
1187            }
1188          };
1189        }
1190
1191        @Override
1192        public int size() {
1193          return map.containsKey(key) ? 1 : 0;
1194        }
1195      };
1196    }
1197
1198    @Override
1199    public boolean put(@ParametricNullness K key, @ParametricNullness V value) {
1200      throw new UnsupportedOperationException();
1201    }
1202
1203    @Override
1204    public boolean putAll(@ParametricNullness K key, Iterable<? extends V> values) {
1205      throw new UnsupportedOperationException();
1206    }
1207
1208    @Override
1209    public boolean putAll(Multimap<? extends K, ? extends V> multimap) {
1210      throw new UnsupportedOperationException();
1211    }
1212
1213    @Override
1214    public Set<V> replaceValues(@ParametricNullness K key, Iterable<? extends V> values) {
1215      throw new UnsupportedOperationException();
1216    }
1217
1218    @Override
1219    public boolean remove(@Nullable Object key, @Nullable Object value) {
1220      return map.entrySet().remove(Maps.immutableEntry(key, value));
1221    }
1222
1223    @Override
1224    public Set<V> removeAll(@Nullable Object key) {
1225      Set<V> values = new HashSet<>(2);
1226      if (!map.containsKey(key)) {
1227        return values;
1228      }
1229      values.add(map.remove(key));
1230      return values;
1231    }
1232
1233    @Override
1234    public void clear() {
1235      map.clear();
1236    }
1237
1238    @Override
1239    Set<K> createKeySet() {
1240      return map.keySet();
1241    }
1242
1243    @Override
1244    Collection<V> createValues() {
1245      return map.values();
1246    }
1247
1248    @Override
1249    public Set<Entry<K, V>> entries() {
1250      return map.entrySet();
1251    }
1252
1253    @Override
1254    Collection<Entry<K, V>> createEntries() {
1255      throw new AssertionError("unreachable");
1256    }
1257
1258    @Override
1259    Multiset<K> createKeys() {
1260      return new Multimaps.Keys<K, V>(this);
1261    }
1262
1263    @Override
1264    Iterator<Entry<K, V>> entryIterator() {
1265      return map.entrySet().iterator();
1266    }
1267
1268    @Override
1269    Map<K, Collection<V>> createAsMap() {
1270      return new AsMap<>(this);
1271    }
1272
1273    @Override
1274    public int hashCode() {
1275      return map.hashCode();
1276    }
1277
1278    @GwtIncompatible @J2ktIncompatible
1279    private static final long serialVersionUID = 7845222491160860175L;
1280  }
1281
1282  /**
1283   * Returns a view of a multimap where each value is transformed by a function. All other
1284   * properties of the multimap, such as iteration order, are left intact. For example, the code:
1285   *
1286   * <pre>{@code
1287   * Multimap<String, Integer> multimap =
1288   *     ImmutableSetMultimap.of("a", 2, "b", -3, "b", -3, "a", 4, "c", 6);
1289   * Function<Integer, String> square = new Function<Integer, String>() {
1290   *     public String apply(Integer in) {
1291   *       return Integer.toString(in * in);
1292   *     }
1293   * };
1294   * Multimap<String, String> transformed =
1295   *     Multimaps.transformValues(multimap, square);
1296   *   System.out.println(transformed);
1297   * }</pre>
1298   *
1299   * ... prints {@code {a=[4, 16], b=[9, 9], c=[36]}}.
1300   *
1301   * <p>Changes in the underlying multimap are reflected in this view. Conversely, this view
1302   * supports removal operations, and these are reflected in the underlying multimap.
1303   *
1304   * <p>It's acceptable for the underlying multimap to contain null keys, and even null values
1305   * provided that the function is capable of accepting null input. The transformed multimap might
1306   * contain null values, if the function sometimes gives a null result.
1307   *
1308   * <p>The returned multimap is not thread-safe or serializable, even if the underlying multimap
1309   * is. The {@code equals} and {@code hashCode} methods of the returned multimap are meaningless,
1310   * since there is not a definition of {@code equals} or {@code hashCode} for general collections,
1311   * and {@code get()} will return a general {@code Collection} as opposed to a {@code List} or a
1312   * {@code Set}.
1313   *
1314   * <p>The function is applied lazily, invoked when needed. This is necessary for the returned
1315   * multimap to be a view, but it means that the function will be applied many times for bulk
1316   * operations like {@link Multimap#containsValue} and {@code Multimap.toString()}. For this to
1317   * perform well, {@code function} should be fast. To avoid lazy evaluation when the returned
1318   * multimap doesn't need to be a view, copy the returned multimap into a new multimap of your
1319   * choosing.
1320   *
1321   * @since 7.0
1322   */
1323  public static <
1324          K extends @Nullable Object, V1 extends @Nullable Object, V2 extends @Nullable Object>
1325      Multimap<K, V2> transformValues(
1326          Multimap<K, V1> fromMultimap, Function<? super V1, V2> function) {
1327    checkNotNull(function);
1328    EntryTransformer<K, V1, V2> transformer = (key, value) -> function.apply(value);
1329    return transformEntries(fromMultimap, transformer);
1330  }
1331
1332  /**
1333   * Returns a view of a {@code ListMultimap} where each value is transformed by a function. All
1334   * other properties of the multimap, such as iteration order, are left intact. For example, the
1335   * code:
1336   *
1337   * <pre>{@code
1338   * ListMultimap<String, Integer> multimap =
1339   *      ImmutableListMultimap.of("a", 4, "a", 16, "b", 9);
1340   * Function<Integer, Double> sqrt = (Integer in) -> Math.sqrt((int) in);
1341   * ListMultimap<String, Double> transformed = Multimaps.transformValues(map,
1342   *     sqrt);
1343   * System.out.println(transformed);
1344   * }</pre>
1345   *
1346   * ... prints {@code {a=[2.0, 4.0], b=[3.0]}}.
1347   *
1348   * <p>Changes in the underlying multimap are reflected in this view. Conversely, this view
1349   * supports removal operations, and these are reflected in the underlying multimap.
1350   *
1351   * <p>It's acceptable for the underlying multimap to contain null keys, and even null values
1352   * provided that the function is capable of accepting null input. The transformed multimap might
1353   * contain null values, if the function sometimes gives a null result.
1354   *
1355   * <p>The returned multimap is not thread-safe or serializable, even if the underlying multimap
1356   * is.
1357   *
1358   * <p>The function is applied lazily, invoked when needed. This is necessary for the returned
1359   * multimap to be a view, but it means that the function will be applied many times for bulk
1360   * operations like {@link Multimap#containsValue} and {@code Multimap.toString()}. For this to
1361   * perform well, {@code function} should be fast. To avoid lazy evaluation when the returned
1362   * multimap doesn't need to be a view, copy the returned multimap into a new multimap of your
1363   * choosing.
1364   *
1365   * @since 7.0
1366   */
1367  public static <
1368          K extends @Nullable Object, V1 extends @Nullable Object, V2 extends @Nullable Object>
1369      ListMultimap<K, V2> transformValues(
1370          ListMultimap<K, V1> fromMultimap, Function<? super V1, V2> function) {
1371    checkNotNull(function);
1372    EntryTransformer<K, V1, V2> transformer = (key, value) -> function.apply(value);
1373    return transformEntries(fromMultimap, transformer);
1374  }
1375
1376  /**
1377   * Returns a view of a multimap whose values are derived from the original multimap's entries. In
1378   * contrast to {@link #transformValues}, this method's entry-transformation logic may depend on
1379   * the key as well as the value.
1380   *
1381   * <p>All other properties of the transformed multimap, such as iteration order, are left intact.
1382   * For example, the code:
1383   *
1384   * <pre>{@code
1385   * SetMultimap<String, Integer> multimap =
1386   *     ImmutableSetMultimap.of("a", 1, "a", 4, "b", -6);
1387   * EntryTransformer<String, Integer, String> transformer =
1388   *     new EntryTransformer<String, Integer, String>() {
1389   *       public String transformEntry(String key, Integer value) {
1390   *          return (value >= 0) ? key : "no" + key;
1391   *       }
1392   *     };
1393   * Multimap<String, String> transformed =
1394   *     Multimaps.transformEntries(multimap, transformer);
1395   * System.out.println(transformed);
1396   * }</pre>
1397   *
1398   * ... prints {@code {a=[a, a], b=[nob]}}.
1399   *
1400   * <p>Changes in the underlying multimap are reflected in this view. Conversely, this view
1401   * supports removal operations, and these are reflected in the underlying multimap.
1402   *
1403   * <p>It's acceptable for the underlying multimap to contain null keys and null values provided
1404   * that the transformer is capable of accepting null inputs. The transformed multimap might
1405   * contain null values if the transformer sometimes gives a null result.
1406   *
1407   * <p>The returned multimap is not thread-safe or serializable, even if the underlying multimap
1408   * is. The {@code equals} and {@code hashCode} methods of the returned multimap are meaningless,
1409   * since there is not a definition of {@code equals} or {@code hashCode} for general collections,
1410   * and {@code get()} will return a general {@code Collection} as opposed to a {@code List} or a
1411   * {@code Set}.
1412   *
1413   * <p>The transformer is applied lazily, invoked when needed. This is necessary for the returned
1414   * multimap to be a view, but it means that the transformer will be applied many times for bulk
1415   * operations like {@link Multimap#containsValue} and {@link Object#toString}. For this to perform
1416   * well, {@code transformer} should be fast. To avoid lazy evaluation when the returned multimap
1417   * doesn't need to be a view, copy the returned multimap into a new multimap of your choosing.
1418   *
1419   * <p><b>Warning:</b> This method assumes that for any instance {@code k} of {@code
1420   * EntryTransformer} key type {@code K}, {@code k.equals(k2)} implies that {@code k2} is also of
1421   * type {@code K}. Using an {@code EntryTransformer} key type for which this may not hold, such as
1422   * {@code ArrayList}, may risk a {@code ClassCastException} when calling methods on the
1423   * transformed multimap.
1424   *
1425   * @since 7.0
1426   */
1427  public static <
1428          K extends @Nullable Object, V1 extends @Nullable Object, V2 extends @Nullable Object>
1429      Multimap<K, V2> transformEntries(
1430          Multimap<K, V1> fromMap, EntryTransformer<? super K, ? super V1, V2> transformer) {
1431    return new TransformedEntriesMultimap<>(fromMap, transformer);
1432  }
1433
1434  /**
1435   * Returns a view of a {@code ListMultimap} whose values are derived from the original multimap's
1436   * entries. In contrast to {@link #transformValues(ListMultimap, Function)}, this method's
1437   * entry-transformation logic may depend on the key as well as the value.
1438   *
1439   * <p>All other properties of the transformed multimap, such as iteration order, are left intact.
1440   * For example, the code:
1441   *
1442   * <pre>{@code
1443   * Multimap<String, Integer> multimap =
1444   *     ImmutableMultimap.of("a", 1, "a", 4, "b", 6);
1445   * EntryTransformer<String, Integer, String> transformer =
1446   *     new EntryTransformer<String, Integer, String>() {
1447   *       public String transformEntry(String key, Integer value) {
1448   *         return key + value;
1449   *       }
1450   *     };
1451   * Multimap<String, String> transformed =
1452   *     Multimaps.transformEntries(multimap, transformer);
1453   * System.out.println(transformed);
1454   * }</pre>
1455   *
1456   * ... prints {@code {"a"=["a1", "a4"], "b"=["b6"]}}.
1457   *
1458   * <p>Changes in the underlying multimap are reflected in this view. Conversely, this view
1459   * supports removal operations, and these are reflected in the underlying multimap.
1460   *
1461   * <p>It's acceptable for the underlying multimap to contain null keys and null values provided
1462   * that the transformer is capable of accepting null inputs. The transformed multimap might
1463   * contain null values if the transformer sometimes gives a null result.
1464   *
1465   * <p>The returned multimap is not thread-safe or serializable, even if the underlying multimap
1466   * is.
1467   *
1468   * <p>The transformer is applied lazily, invoked when needed. This is necessary for the returned
1469   * multimap to be a view, but it means that the transformer will be applied many times for bulk
1470   * operations like {@link Multimap#containsValue} and {@link Object#toString}. For this to perform
1471   * well, {@code transformer} should be fast. To avoid lazy evaluation when the returned multimap
1472   * doesn't need to be a view, copy the returned multimap into a new multimap of your choosing.
1473   *
1474   * <p><b>Warning:</b> This method assumes that for any instance {@code k} of {@code
1475   * EntryTransformer} key type {@code K}, {@code k.equals(k2)} implies that {@code k2} is also of
1476   * type {@code K}. Using an {@code EntryTransformer} key type for which this may not hold, such as
1477   * {@code ArrayList}, may risk a {@code ClassCastException} when calling methods on the
1478   * transformed multimap.
1479   *
1480   * @since 7.0
1481   */
1482  public static <
1483          K extends @Nullable Object, V1 extends @Nullable Object, V2 extends @Nullable Object>
1484      ListMultimap<K, V2> transformEntries(
1485          ListMultimap<K, V1> fromMap, EntryTransformer<? super K, ? super V1, V2> transformer) {
1486    return new TransformedEntriesListMultimap<>(fromMap, transformer);
1487  }
1488
1489  private static class TransformedEntriesMultimap<
1490          K extends @Nullable Object, V1 extends @Nullable Object, V2 extends @Nullable Object>
1491      extends AbstractMultimap<K, V2> {
1492    final Multimap<K, V1> fromMultimap;
1493    final EntryTransformer<? super K, ? super V1, V2> transformer;
1494
1495    TransformedEntriesMultimap(
1496        Multimap<K, V1> fromMultimap, EntryTransformer<? super K, ? super V1, V2> transformer) {
1497      this.fromMultimap = checkNotNull(fromMultimap);
1498      this.transformer = checkNotNull(transformer);
1499    }
1500
1501    Collection<V2> transform(@ParametricNullness K key, Collection<V1> values) {
1502      Function<? super V1, V2> function = v1 -> transformer.transformEntry(key, v1);
1503      if (values instanceof List) {
1504        return Lists.transform((List<V1>) values, function);
1505      } else {
1506        return Collections2.transform(values, function);
1507      }
1508    }
1509
1510    @Override
1511    Map<K, Collection<V2>> createAsMap() {
1512      return Maps.transformEntries(fromMultimap.asMap(), this::transform);
1513    }
1514
1515    @Override
1516    public void clear() {
1517      fromMultimap.clear();
1518    }
1519
1520    @Override
1521    public boolean containsKey(@Nullable Object key) {
1522      return fromMultimap.containsKey(key);
1523    }
1524
1525    @Override
1526    Collection<Entry<K, V2>> createEntries() {
1527      return new Entries();
1528    }
1529
1530    @Override
1531    Iterator<Entry<K, V2>> entryIterator() {
1532      return Iterators.transform(
1533          fromMultimap.entries().iterator(), Maps.<K, V1, V2>asEntryToEntryFunction(transformer));
1534    }
1535
1536    @Override
1537    public Collection<V2> get(@ParametricNullness K key) {
1538      return transform(key, fromMultimap.get(key));
1539    }
1540
1541    @Override
1542    public boolean isEmpty() {
1543      return fromMultimap.isEmpty();
1544    }
1545
1546    @Override
1547    Set<K> createKeySet() {
1548      return fromMultimap.keySet();
1549    }
1550
1551    @Override
1552    Multiset<K> createKeys() {
1553      return fromMultimap.keys();
1554    }
1555
1556    @Override
1557    public boolean put(@ParametricNullness K key, @ParametricNullness V2 value) {
1558      throw new UnsupportedOperationException();
1559    }
1560
1561    @Override
1562    public boolean putAll(@ParametricNullness K key, Iterable<? extends V2> values) {
1563      throw new UnsupportedOperationException();
1564    }
1565
1566    @Override
1567    public boolean putAll(Multimap<? extends K, ? extends V2> multimap) {
1568      throw new UnsupportedOperationException();
1569    }
1570
1571    @SuppressWarnings("unchecked")
1572    @Override
1573    public boolean remove(@Nullable Object key, @Nullable Object value) {
1574      return get((K) key).remove(value);
1575    }
1576
1577    @SuppressWarnings("unchecked")
1578    @Override
1579    public Collection<V2> removeAll(@Nullable Object key) {
1580      return transform((K) key, fromMultimap.removeAll(key));
1581    }
1582
1583    @Override
1584    public Collection<V2> replaceValues(@ParametricNullness K key, Iterable<? extends V2> values) {
1585      throw new UnsupportedOperationException();
1586    }
1587
1588    @Override
1589    public int size() {
1590      return fromMultimap.size();
1591    }
1592
1593    @Override
1594    Collection<V2> createValues() {
1595      return Collections2.transform(
1596          fromMultimap.entries(),
1597          entry -> transformer.transformEntry(entry.getKey(), entry.getValue()));
1598    }
1599  }
1600
1601  private static final class TransformedEntriesListMultimap<
1602          K extends @Nullable Object, V1 extends @Nullable Object, V2 extends @Nullable Object>
1603      extends TransformedEntriesMultimap<K, V1, V2> implements ListMultimap<K, V2> {
1604
1605    TransformedEntriesListMultimap(
1606        ListMultimap<K, V1> fromMultimap, EntryTransformer<? super K, ? super V1, V2> transformer) {
1607      super(fromMultimap, transformer);
1608    }
1609
1610    @Override
1611    List<V2> transform(@ParametricNullness K key, Collection<V1> values) {
1612      return Lists.transform((List<V1>) values, v1 -> transformer.transformEntry(key, v1));
1613    }
1614
1615    @Override
1616    public List<V2> get(@ParametricNullness K key) {
1617      return transform(key, fromMultimap.get(key));
1618    }
1619
1620    @SuppressWarnings("unchecked")
1621    @Override
1622    public List<V2> removeAll(@Nullable Object key) {
1623      return transform((K) key, fromMultimap.removeAll(key));
1624    }
1625
1626    @Override
1627    public List<V2> replaceValues(@ParametricNullness K key, Iterable<? extends V2> values) {
1628      throw new UnsupportedOperationException();
1629    }
1630  }
1631
1632  /**
1633   * Creates an index {@code ImmutableListMultimap} that contains the results of applying a
1634   * specified function to each item in an {@code Iterable} of values. Each value will be stored as
1635   * a value in the resulting multimap, yielding a multimap with the same size as the input
1636   * iterable. The key used to store that value in the multimap will be the result of calling the
1637   * function on that value. The resulting multimap is created as an immutable snapshot. In the
1638   * returned multimap, keys appear in the order they are first encountered, and the values
1639   * corresponding to each key appear in the same order as they are encountered.
1640   *
1641   * <p>For example,
1642   *
1643   * <pre>{@code
1644   * List<String> badGuys =
1645   *     Arrays.asList("Inky", "Blinky", "Pinky", "Pinky", "Clyde");
1646   * Function<String, Integer> stringLengthFunction = ...;
1647   * Multimap<Integer, String> index =
1648   *     Multimaps.index(badGuys, stringLengthFunction);
1649   * System.out.println(index);
1650   * }</pre>
1651   *
1652   * <p>prints
1653   *
1654   * <pre>{@code
1655   * {4=[Inky], 6=[Blinky], 5=[Pinky, Pinky, Clyde]}
1656   * }</pre>
1657   *
1658   * <p>The returned multimap is serializable if its keys and values are all serializable.
1659   *
1660   * @param values the values to use when constructing the {@code ImmutableListMultimap}
1661   * @param keyFunction the function used to produce the key for each value
1662   * @return {@code ImmutableListMultimap} mapping the result of evaluating the function {@code
1663   *     keyFunction} on each value in the input collection to that value
1664   * @throws NullPointerException if any element of {@code values} is {@code null}, or if {@code
1665   *     keyFunction} produces {@code null} for any key
1666   */
1667  public static <K, V> ImmutableListMultimap<K, V> index(
1668      Iterable<V> values, Function<? super V, K> keyFunction) {
1669    return index(values.iterator(), keyFunction);
1670  }
1671
1672  /**
1673   * Creates an index {@code ImmutableListMultimap} that contains the results of applying a
1674   * specified function to each item in an {@code Iterator} of values. Each value will be stored as
1675   * a value in the resulting multimap, yielding a multimap with the same size as the input
1676   * iterator. The key used to store that value in the multimap will be the result of calling the
1677   * function on that value. The resulting multimap is created as an immutable snapshot. In the
1678   * returned multimap, keys appear in the order they are first encountered, and the values
1679   * corresponding to each key appear in the same order as they are encountered.
1680   *
1681   * <p>For example,
1682   *
1683   * <pre>{@code
1684   * List<String> badGuys =
1685   *     Arrays.asList("Inky", "Blinky", "Pinky", "Pinky", "Clyde");
1686   * Function<String, Integer> stringLengthFunction = ...;
1687   * Multimap<Integer, String> index =
1688   *     Multimaps.index(badGuys.iterator(), stringLengthFunction);
1689   * System.out.println(index);
1690   * }</pre>
1691   *
1692   * <p>prints
1693   *
1694   * <pre>{@code
1695   * {4=[Inky], 6=[Blinky], 5=[Pinky, Pinky, Clyde]}
1696   * }</pre>
1697   *
1698   * <p>The returned multimap is serializable if its keys and values are all serializable.
1699   *
1700   * @param values the values to use when constructing the {@code ImmutableListMultimap}
1701   * @param keyFunction the function used to produce the key for each value
1702   * @return {@code ImmutableListMultimap} mapping the result of evaluating the function {@code
1703   *     keyFunction} on each value in the input collection to that value
1704   * @throws NullPointerException if any element of {@code values} is {@code null}, or if {@code
1705   *     keyFunction} produces {@code null} for any key
1706   * @since 10.0
1707   */
1708  public static <K, V> ImmutableListMultimap<K, V> index(
1709      Iterator<V> values, Function<? super V, K> keyFunction) {
1710    checkNotNull(keyFunction);
1711    ImmutableListMultimap.Builder<K, V> builder = ImmutableListMultimap.builder();
1712    while (values.hasNext()) {
1713      V value = values.next();
1714      checkNotNull(value, values);
1715      builder.put(keyFunction.apply(value), value);
1716    }
1717    return builder.build();
1718  }
1719
1720  static class Keys<K extends @Nullable Object, V extends @Nullable Object>
1721      extends AbstractMultiset<K> {
1722    @Weak final Multimap<K, V> multimap;
1723
1724    Keys(Multimap<K, V> multimap) {
1725      this.multimap = multimap;
1726    }
1727
1728    @Override
1729    Iterator<Multiset.Entry<K>> entryIterator() {
1730      return new TransformedIterator<Map.Entry<K, Collection<V>>, Multiset.Entry<K>>(
1731          multimap.asMap().entrySet().iterator()) {
1732        @Override
1733        Multiset.Entry<K> transform(Map.Entry<K, Collection<V>> backingEntry) {
1734          return new Multisets.AbstractEntry<K>() {
1735            @Override
1736            @ParametricNullness
1737            public K getElement() {
1738              return backingEntry.getKey();
1739            }
1740
1741            @Override
1742            public int getCount() {
1743              return backingEntry.getValue().size();
1744            }
1745          };
1746        }
1747      };
1748    }
1749
1750    @Override
1751    int distinctElements() {
1752      return multimap.asMap().size();
1753    }
1754
1755    @Override
1756    public int size() {
1757      return multimap.size();
1758    }
1759
1760    @Override
1761    public boolean contains(@Nullable Object element) {
1762      return multimap.containsKey(element);
1763    }
1764
1765    @Override
1766    public Iterator<K> iterator() {
1767      return Maps.keyIterator(multimap.entries().iterator());
1768    }
1769
1770    @Override
1771    public int count(@Nullable Object element) {
1772      Collection<V> values = Maps.safeGet(multimap.asMap(), element);
1773      return (values == null) ? 0 : values.size();
1774    }
1775
1776    @Override
1777    public int remove(@Nullable Object element, int occurrences) {
1778      checkNonnegative(occurrences, "occurrences");
1779      if (occurrences == 0) {
1780        return count(element);
1781      }
1782
1783      Collection<V> values = Maps.safeGet(multimap.asMap(), element);
1784
1785      if (values == null) {
1786        return 0;
1787      }
1788
1789      int oldCount = values.size();
1790      if (occurrences >= oldCount) {
1791        values.clear();
1792      } else {
1793        Iterator<V> iterator = values.iterator();
1794        for (int i = 0; i < occurrences; i++) {
1795          iterator.next();
1796          iterator.remove();
1797        }
1798      }
1799      return oldCount;
1800    }
1801
1802    @Override
1803    public void clear() {
1804      multimap.clear();
1805    }
1806
1807    @Override
1808    public Set<K> elementSet() {
1809      return multimap.keySet();
1810    }
1811
1812    @Override
1813    Iterator<K> elementIterator() {
1814      throw new AssertionError("should never be called");
1815    }
1816  }
1817
1818  /** A skeleton implementation of {@link Multimap#entries()}. */
1819  abstract static class Entries<K extends @Nullable Object, V extends @Nullable Object>
1820      extends AbstractCollection<Map.Entry<K, V>> {
1821    abstract Multimap<K, V> multimap();
1822
1823    @Override
1824    public int size() {
1825      return multimap().size();
1826    }
1827
1828    @Override
1829    public boolean contains(@Nullable Object o) {
1830      if (o instanceof Map.Entry) {
1831        Map.Entry<?, ?> entry = (Map.Entry<?, ?>) o;
1832        return multimap().containsEntry(entry.getKey(), entry.getValue());
1833      }
1834      return false;
1835    }
1836
1837    @Override
1838    public boolean remove(@Nullable Object o) {
1839      if (o instanceof Map.Entry) {
1840        Map.Entry<?, ?> entry = (Map.Entry<?, ?>) o;
1841        return multimap().remove(entry.getKey(), entry.getValue());
1842      }
1843      return false;
1844    }
1845
1846    @Override
1847    public void clear() {
1848      multimap().clear();
1849    }
1850  }
1851
1852  /** A skeleton implementation of {@link Multimap#asMap()}. */
1853  static final class AsMap<K extends @Nullable Object, V extends @Nullable Object>
1854      extends Maps.ViewCachingAbstractMap<K, Collection<V>> {
1855    @Weak private final Multimap<K, V> multimap;
1856
1857    AsMap(Multimap<K, V> multimap) {
1858      this.multimap = checkNotNull(multimap);
1859    }
1860
1861    @Override
1862    public int size() {
1863      return multimap.keySet().size();
1864    }
1865
1866    @Override
1867    protected Set<Entry<K, Collection<V>>> createEntrySet() {
1868      return new EntrySet();
1869    }
1870
1871    void removeValuesForKey(@Nullable Object key) {
1872      multimap.keySet().remove(key);
1873    }
1874
1875    @WeakOuter
1876    class EntrySet extends Maps.EntrySet<K, Collection<V>> {
1877      @Override
1878      Map<K, Collection<V>> map() {
1879        return AsMap.this;
1880      }
1881
1882      @Override
1883      public Iterator<Entry<K, Collection<V>>> iterator() {
1884        return Maps.asMapEntryIterator(multimap.keySet(), multimap::get);
1885      }
1886
1887      @Override
1888      public boolean remove(@Nullable Object o) {
1889        if (!contains(o)) {
1890          return false;
1891        }
1892        // requireNonNull is safe because of the contains check.
1893        Map.Entry<?, ?> entry = requireNonNull((Map.Entry<?, ?>) o);
1894        removeValuesForKey(entry.getKey());
1895        return true;
1896      }
1897    }
1898
1899    @SuppressWarnings("unchecked")
1900    @Override
1901    public @Nullable Collection<V> get(@Nullable Object key) {
1902      return containsKey(key) ? multimap.get((K) key) : null;
1903    }
1904
1905    @Override
1906    public @Nullable Collection<V> remove(@Nullable Object key) {
1907      return containsKey(key) ? multimap.removeAll(key) : null;
1908    }
1909
1910    @Override
1911    public Set<K> keySet() {
1912      return multimap.keySet();
1913    }
1914
1915    @Override
1916    public boolean isEmpty() {
1917      return multimap.isEmpty();
1918    }
1919
1920    @Override
1921    public boolean containsKey(@Nullable Object key) {
1922      return multimap.containsKey(key);
1923    }
1924
1925    @Override
1926    public void clear() {
1927      multimap.clear();
1928    }
1929  }
1930
1931  /**
1932   * Returns a multimap containing the mappings in {@code unfiltered} whose keys satisfy a
1933   * predicate. The returned multimap is a live view of {@code unfiltered}; changes to one affect
1934   * the other.
1935   *
1936   * <p>The resulting multimap's views have iterators that don't support {@code remove()}, but all
1937   * other methods are supported by the multimap and its views. When adding a key that doesn't
1938   * satisfy the predicate, the multimap's {@code put()}, {@code putAll()}, and {@code
1939   * replaceValues()} methods throw an {@link IllegalArgumentException}.
1940   *
1941   * <p>When methods such as {@code removeAll()} and {@code clear()} are called on the filtered
1942   * multimap or its views, only mappings whose keys satisfy the filter will be removed from the
1943   * underlying multimap.
1944   *
1945   * <p>The returned multimap isn't threadsafe or serializable, even if {@code unfiltered} is.
1946   *
1947   * <p>Many of the filtered multimap's methods, such as {@code size()}, iterate across every
1948   * key/value mapping in the underlying multimap and determine which satisfy the filter. When a
1949   * live view is <i>not</i> needed, it may be faster to copy the filtered multimap and use the
1950   * copy.
1951   *
1952   * <p><b>Warning:</b> {@code keyPredicate} must be <i>consistent with equals</i>, as documented at
1953   * {@link Predicate#apply}. Do not provide a predicate such as {@code
1954   * Predicates.instanceOf(ArrayList.class)}, which is inconsistent with equals.
1955   *
1956   * @since 11.0
1957   */
1958  public static <K extends @Nullable Object, V extends @Nullable Object> Multimap<K, V> filterKeys(
1959      Multimap<K, V> unfiltered, Predicate<? super K> keyPredicate) {
1960    if (unfiltered instanceof SetMultimap) {
1961      return filterKeys((SetMultimap<K, V>) unfiltered, keyPredicate);
1962    } else if (unfiltered instanceof ListMultimap) {
1963      return filterKeys((ListMultimap<K, V>) unfiltered, keyPredicate);
1964    } else if (unfiltered instanceof FilteredKeyMultimap) {
1965      FilteredKeyMultimap<K, V> prev = (FilteredKeyMultimap<K, V>) unfiltered;
1966      return new FilteredKeyMultimap<>(
1967          prev.unfiltered, Predicates.<K>and(prev.keyPredicate, keyPredicate));
1968    } else if (unfiltered instanceof FilteredMultimap) {
1969      FilteredMultimap<K, V> prev = (FilteredMultimap<K, V>) unfiltered;
1970      return filterFiltered(prev, Maps.<K>keyPredicateOnEntries(keyPredicate));
1971    } else {
1972      return new FilteredKeyMultimap<>(unfiltered, keyPredicate);
1973    }
1974  }
1975
1976  /**
1977   * Returns a multimap containing the mappings in {@code unfiltered} whose keys satisfy a
1978   * predicate. The returned multimap is a live view of {@code unfiltered}; changes to one affect
1979   * the other.
1980   *
1981   * <p>The resulting multimap's views have iterators that don't support {@code remove()}, but all
1982   * other methods are supported by the multimap and its views. When adding a key that doesn't
1983   * satisfy the predicate, the multimap's {@code put()}, {@code putAll()}, and {@code
1984   * replaceValues()} methods throw an {@link IllegalArgumentException}.
1985   *
1986   * <p>When methods such as {@code removeAll()} and {@code clear()} are called on the filtered
1987   * multimap or its views, only mappings whose keys satisfy the filter will be removed from the
1988   * underlying multimap.
1989   *
1990   * <p>The returned multimap isn't threadsafe or serializable, even if {@code unfiltered} is.
1991   *
1992   * <p>Many of the filtered multimap's methods, such as {@code size()}, iterate across every
1993   * key/value mapping in the underlying multimap and determine which satisfy the filter. When a
1994   * live view is <i>not</i> needed, it may be faster to copy the filtered multimap and use the
1995   * copy.
1996   *
1997   * <p><b>Warning:</b> {@code keyPredicate} must be <i>consistent with equals</i>, as documented at
1998   * {@link Predicate#apply}. Do not provide a predicate such as {@code
1999   * Predicates.instanceOf(ArrayList.class)}, which is inconsistent with equals.
2000   *
2001   * @since 14.0
2002   */
2003  public static <K extends @Nullable Object, V extends @Nullable Object>
2004      SetMultimap<K, V> filterKeys(
2005          SetMultimap<K, V> unfiltered, Predicate<? super K> keyPredicate) {
2006    if (unfiltered instanceof FilteredKeySetMultimap) {
2007      FilteredKeySetMultimap<K, V> prev = (FilteredKeySetMultimap<K, V>) unfiltered;
2008      return new FilteredKeySetMultimap<>(
2009          prev.unfiltered(), Predicates.<K>and(prev.keyPredicate, keyPredicate));
2010    } else if (unfiltered instanceof FilteredSetMultimap) {
2011      FilteredSetMultimap<K, V> prev = (FilteredSetMultimap<K, V>) unfiltered;
2012      return filterFiltered(prev, Maps.<K>keyPredicateOnEntries(keyPredicate));
2013    } else {
2014      return new FilteredKeySetMultimap<>(unfiltered, keyPredicate);
2015    }
2016  }
2017
2018  /**
2019   * Returns a multimap containing the mappings in {@code unfiltered} whose keys satisfy a
2020   * predicate. The returned multimap is a live view of {@code unfiltered}; changes to one affect
2021   * the other.
2022   *
2023   * <p>The resulting multimap's views have iterators that don't support {@code remove()}, but all
2024   * other methods are supported by the multimap and its views. When adding a key that doesn't
2025   * satisfy the predicate, the multimap's {@code put()}, {@code putAll()}, and {@code
2026   * replaceValues()} methods throw an {@link IllegalArgumentException}.
2027   *
2028   * <p>When methods such as {@code removeAll()} and {@code clear()} are called on the filtered
2029   * multimap or its views, only mappings whose keys satisfy the filter will be removed from the
2030   * underlying multimap.
2031   *
2032   * <p>The returned multimap isn't threadsafe or serializable, even if {@code unfiltered} is.
2033   *
2034   * <p>Many of the filtered multimap's methods, such as {@code size()}, iterate across every
2035   * key/value mapping in the underlying multimap and determine which satisfy the filter. When a
2036   * live view is <i>not</i> needed, it may be faster to copy the filtered multimap and use the
2037   * copy.
2038   *
2039   * <p><b>Warning:</b> {@code keyPredicate} must be <i>consistent with equals</i>, as documented at
2040   * {@link Predicate#apply}. Do not provide a predicate such as {@code
2041   * Predicates.instanceOf(ArrayList.class)}, which is inconsistent with equals.
2042   *
2043   * @since 14.0
2044   */
2045  public static <K extends @Nullable Object, V extends @Nullable Object>
2046      ListMultimap<K, V> filterKeys(
2047          ListMultimap<K, V> unfiltered, Predicate<? super K> keyPredicate) {
2048    if (unfiltered instanceof FilteredKeyListMultimap) {
2049      FilteredKeyListMultimap<K, V> prev = (FilteredKeyListMultimap<K, V>) unfiltered;
2050      return new FilteredKeyListMultimap<>(
2051          prev.unfiltered(), Predicates.<K>and(prev.keyPredicate, keyPredicate));
2052    } else {
2053      return new FilteredKeyListMultimap<>(unfiltered, keyPredicate);
2054    }
2055  }
2056
2057  /**
2058   * Returns a multimap containing the mappings in {@code unfiltered} whose values satisfy a
2059   * predicate. The returned multimap is a live view of {@code unfiltered}; changes to one affect
2060   * the other.
2061   *
2062   * <p>The resulting multimap's views have iterators that don't support {@code remove()}, but all
2063   * other methods are supported by the multimap and its views. When adding a value that doesn't
2064   * satisfy the predicate, the multimap's {@code put()}, {@code putAll()}, and {@code
2065   * replaceValues()} methods throw an {@link IllegalArgumentException}.
2066   *
2067   * <p>When methods such as {@code removeAll()} and {@code clear()} are called on the filtered
2068   * multimap or its views, only mappings whose value satisfy the filter will be removed from the
2069   * underlying multimap.
2070   *
2071   * <p>The returned multimap isn't threadsafe or serializable, even if {@code unfiltered} is.
2072   *
2073   * <p>Many of the filtered multimap's methods, such as {@code size()}, iterate across every
2074   * key/value mapping in the underlying multimap and determine which satisfy the filter. When a
2075   * live view is <i>not</i> needed, it may be faster to copy the filtered multimap and use the
2076   * copy.
2077   *
2078   * <p><b>Warning:</b> {@code valuePredicate} must be <i>consistent with equals</i>, as documented
2079   * at {@link Predicate#apply}. Do not provide a predicate such as {@code
2080   * Predicates.instanceOf(ArrayList.class)}, which is inconsistent with equals.
2081   *
2082   * @since 11.0
2083   */
2084  public static <K extends @Nullable Object, V extends @Nullable Object>
2085      Multimap<K, V> filterValues(Multimap<K, V> unfiltered, Predicate<? super V> valuePredicate) {
2086    return filterEntries(unfiltered, Maps.<V>valuePredicateOnEntries(valuePredicate));
2087  }
2088
2089  /**
2090   * Returns a multimap containing the mappings in {@code unfiltered} whose values satisfy a
2091   * predicate. The returned multimap is a live view of {@code unfiltered}; changes to one affect
2092   * the other.
2093   *
2094   * <p>The resulting multimap's views have iterators that don't support {@code remove()}, but all
2095   * other methods are supported by the multimap and its views. When adding a value that doesn't
2096   * satisfy the predicate, the multimap's {@code put()}, {@code putAll()}, and {@code
2097   * replaceValues()} methods throw an {@link IllegalArgumentException}.
2098   *
2099   * <p>When methods such as {@code removeAll()} and {@code clear()} are called on the filtered
2100   * multimap or its views, only mappings whose value satisfy the filter will be removed from the
2101   * underlying multimap.
2102   *
2103   * <p>The returned multimap isn't threadsafe or serializable, even if {@code unfiltered} is.
2104   *
2105   * <p>Many of the filtered multimap's methods, such as {@code size()}, iterate across every
2106   * key/value mapping in the underlying multimap and determine which satisfy the filter. When a
2107   * live view is <i>not</i> needed, it may be faster to copy the filtered multimap and use the
2108   * copy.
2109   *
2110   * <p><b>Warning:</b> {@code valuePredicate} must be <i>consistent with equals</i>, as documented
2111   * at {@link Predicate#apply}. Do not provide a predicate such as {@code
2112   * Predicates.instanceOf(ArrayList.class)}, which is inconsistent with equals.
2113   *
2114   * @since 14.0
2115   */
2116  public static <K extends @Nullable Object, V extends @Nullable Object>
2117      SetMultimap<K, V> filterValues(
2118          SetMultimap<K, V> unfiltered, Predicate<? super V> valuePredicate) {
2119    return filterEntries(unfiltered, Maps.<V>valuePredicateOnEntries(valuePredicate));
2120  }
2121
2122  /**
2123   * Returns a multimap containing the mappings in {@code unfiltered} that satisfy a predicate. The
2124   * returned multimap is a live view of {@code unfiltered}; changes to one affect the other.
2125   *
2126   * <p>The resulting multimap's views have iterators that don't support {@code remove()}, but all
2127   * other methods are supported by the multimap and its views. When adding a key/value pair that
2128   * doesn't satisfy the predicate, multimap's {@code put()}, {@code putAll()}, and {@code
2129   * replaceValues()} methods throw an {@link IllegalArgumentException}.
2130   *
2131   * <p>When methods such as {@code removeAll()} and {@code clear()} are called on the filtered
2132   * multimap or its views, only mappings whose keys satisfy the filter will be removed from the
2133   * underlying multimap.
2134   *
2135   * <p>The returned multimap isn't threadsafe or serializable, even if {@code unfiltered} is.
2136   *
2137   * <p>Many of the filtered multimap's methods, such as {@code size()}, iterate across every
2138   * key/value mapping in the underlying multimap and determine which satisfy the filter. When a
2139   * live view is <i>not</i> needed, it may be faster to copy the filtered multimap and use the
2140   * copy.
2141   *
2142   * <p><b>Warning:</b> {@code entryPredicate} must be <i>consistent with equals</i>, as documented
2143   * at {@link Predicate#apply}.
2144   *
2145   * @since 11.0
2146   */
2147  public static <K extends @Nullable Object, V extends @Nullable Object>
2148      Multimap<K, V> filterEntries(
2149          Multimap<K, V> unfiltered, Predicate<? super Entry<K, V>> entryPredicate) {
2150    checkNotNull(entryPredicate);
2151    if (unfiltered instanceof SetMultimap) {
2152      return filterEntries((SetMultimap<K, V>) unfiltered, entryPredicate);
2153    }
2154    return (unfiltered instanceof FilteredMultimap)
2155        ? filterFiltered((FilteredMultimap<K, V>) unfiltered, entryPredicate)
2156        : new FilteredEntryMultimap<K, V>(checkNotNull(unfiltered), entryPredicate);
2157  }
2158
2159  /**
2160   * Returns a multimap containing the mappings in {@code unfiltered} that satisfy a predicate. The
2161   * returned multimap is a live view of {@code unfiltered}; changes to one affect the other.
2162   *
2163   * <p>The resulting multimap's views have iterators that don't support {@code remove()}, but all
2164   * other methods are supported by the multimap and its views. When adding a key/value pair that
2165   * doesn't satisfy the predicate, multimap's {@code put()}, {@code putAll()}, and {@code
2166   * replaceValues()} methods throw an {@link IllegalArgumentException}.
2167   *
2168   * <p>When methods such as {@code removeAll()} and {@code clear()} are called on the filtered
2169   * multimap or its views, only mappings whose keys satisfy the filter will be removed from the
2170   * underlying multimap.
2171   *
2172   * <p>The returned multimap isn't threadsafe or serializable, even if {@code unfiltered} is.
2173   *
2174   * <p>Many of the filtered multimap's methods, such as {@code size()}, iterate across every
2175   * key/value mapping in the underlying multimap and determine which satisfy the filter. When a
2176   * live view is <i>not</i> needed, it may be faster to copy the filtered multimap and use the
2177   * copy.
2178   *
2179   * <p><b>Warning:</b> {@code entryPredicate} must be <i>consistent with equals</i>, as documented
2180   * at {@link Predicate#apply}.
2181   *
2182   * @since 14.0
2183   */
2184  public static <K extends @Nullable Object, V extends @Nullable Object>
2185      SetMultimap<K, V> filterEntries(
2186          SetMultimap<K, V> unfiltered, Predicate<? super Entry<K, V>> entryPredicate) {
2187    checkNotNull(entryPredicate);
2188    return (unfiltered instanceof FilteredSetMultimap)
2189        ? filterFiltered((FilteredSetMultimap<K, V>) unfiltered, entryPredicate)
2190        : new FilteredEntrySetMultimap<K, V>(checkNotNull(unfiltered), entryPredicate);
2191  }
2192
2193  /**
2194   * Support removal operations when filtering a filtered multimap. Since a filtered multimap has
2195   * iterators that don't support remove, passing one to the FilteredEntryMultimap constructor would
2196   * lead to a multimap whose removal operations would fail. This method combines the predicates to
2197   * avoid that problem.
2198   */
2199  private static <K extends @Nullable Object, V extends @Nullable Object>
2200      Multimap<K, V> filterFiltered(
2201          FilteredMultimap<K, V> multimap, Predicate<? super Entry<K, V>> entryPredicate) {
2202    Predicate<Entry<K, V>> predicate =
2203        Predicates.<Entry<K, V>>and(multimap.entryPredicate(), entryPredicate);
2204    return new FilteredEntryMultimap<>(multimap.unfiltered(), predicate);
2205  }
2206
2207  /**
2208   * Support removal operations when filtering a filtered multimap. Since a filtered multimap has
2209   * iterators that don't support remove, passing one to the FilteredEntryMultimap constructor would
2210   * lead to a multimap whose removal operations would fail. This method combines the predicates to
2211   * avoid that problem.
2212   */
2213  private static <K extends @Nullable Object, V extends @Nullable Object>
2214      SetMultimap<K, V> filterFiltered(
2215          FilteredSetMultimap<K, V> multimap, Predicate<? super Entry<K, V>> entryPredicate) {
2216    Predicate<Entry<K, V>> predicate =
2217        Predicates.<Entry<K, V>>and(multimap.entryPredicate(), entryPredicate);
2218    return new FilteredEntrySetMultimap<>(multimap.unfiltered(), predicate);
2219  }
2220
2221  static boolean equalsImpl(Multimap<?, ?> multimap, @Nullable Object object) {
2222    if (object == multimap) {
2223      return true;
2224    }
2225    if (object instanceof Multimap) {
2226      Multimap<?, ?> that = (Multimap<?, ?>) object;
2227      return multimap.asMap().equals(that.asMap());
2228    }
2229    return false;
2230  }
2231
2232  // TODO(jlevy): Create methods that filter a SortedSetMultimap.
2233}