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