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