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