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