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