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