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