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