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