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