001/*
002 * Copyright (C) 2007 The Guava Authors
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 * http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017package com.google.common.collect;
018
019import static com.google.common.base.Preconditions.checkNotNull;
020import static com.google.common.collect.CollectPreconditions.checkNonnegative;
021import static com.google.common.collect.CollectPreconditions.checkRemove;
022import static com.google.common.collect.NullnessCasts.uncheckedCastNullableTToT;
023import static java.util.Objects.requireNonNull;
024
025import com.google.common.annotations.GwtCompatible;
026import com.google.common.annotations.GwtIncompatible;
027import com.google.common.annotations.J2ktIncompatible;
028import com.google.common.base.Function;
029import com.google.common.base.Predicate;
030import com.google.common.base.Predicates;
031import com.google.common.base.Supplier;
032import com.google.common.collect.Maps.EntryTransformer;
033import com.google.errorprone.annotations.CanIgnoreReturnValue;
034import com.google.errorprone.annotations.concurrent.LazyInit;
035import com.google.j2objc.annotations.Weak;
036import com.google.j2objc.annotations.WeakOuter;
037import java.io.IOException;
038import java.io.ObjectInputStream;
039import java.io.ObjectOutputStream;
040import java.io.Serializable;
041import java.util.AbstractCollection;
042import java.util.Collection;
043import java.util.Collections;
044import java.util.Comparator;
045import java.util.HashSet;
046import java.util.Iterator;
047import java.util.List;
048import java.util.Map;
049import java.util.Map.Entry;
050import java.util.NavigableSet;
051import java.util.NoSuchElementException;
052import java.util.Set;
053import java.util.SortedSet;
054import java.util.stream.Collector;
055import java.util.stream.Stream;
056import javax.annotation.CheckForNull;
057import org.checkerframework.checker.nullness.qual.Nullable;
058
059/**
060 * Provides static methods acting on or generating a {@code Multimap}.
061 *
062 * <p>See the Guava User Guide article on <a href=
063 * "https://github.com/google/guava/wiki/CollectionUtilitiesExplained#multimaps">{@code
064 * Multimaps}</a>.
065 *
066 * @author Jared Levy
067 * @author Robert Konigsberg
068 * @author Mike Bostock
069 * @author Louis Wasserman
070 * @since 2.0
071 */
072@GwtCompatible(emulated = true)
073@ElementTypesAreNonnullByDefault
074public final class Multimaps {
075  private Multimaps() {}
076
077  /**
078   * Returns a {@code Collector} accumulating entries into a {@code Multimap} generated from the
079   * specified supplier. The keys and values of the entries are the result of applying the provided
080   * mapping functions to the input elements, accumulated in the encounter order of the stream.
081   *
082   * <p>Example:
083   *
084   * <pre>{@code
085   * static final ListMultimap<Character, String> FIRST_LETTER_MULTIMAP =
086   *     Stream.of("banana", "apple", "carrot", "asparagus", "cherry")
087   *         .collect(
088   *             toMultimap(
089   *                  str -> str.charAt(0),
090   *                  str -> str.substring(1),
091   *                  MultimapBuilder.treeKeys().arrayListValues()::build));
092   *
093   * // is equivalent to
094   *
095   * static final ListMultimap<Character, String> FIRST_LETTER_MULTIMAP;
096   *
097   * static {
098   *     FIRST_LETTER_MULTIMAP = MultimapBuilder.treeKeys().arrayListValues().build();
099   *     FIRST_LETTER_MULTIMAP.put('b', "anana");
100   *     FIRST_LETTER_MULTIMAP.put('a', "pple");
101   *     FIRST_LETTER_MULTIMAP.put('a', "sparagus");
102   *     FIRST_LETTER_MULTIMAP.put('c', "arrot");
103   *     FIRST_LETTER_MULTIMAP.put('c', "herry");
104   * }
105   * }</pre>
106   *
107   * <p>To collect to an {@link ImmutableMultimap}, use either {@link
108   * ImmutableSetMultimap#toImmutableSetMultimap} or {@link
109   * ImmutableListMultimap#toImmutableListMultimap}.
110   *
111   * @since 33.2.0 (available since 21.0 in guava-jre)
112   */
113  @SuppressWarnings("Java7ApiChecker")
114  @IgnoreJRERequirement // Users will use this only if they're already using streams.
115  public static <
116          T extends @Nullable Object,
117          K extends @Nullable Object,
118          V extends @Nullable Object,
119          M extends Multimap<K, V>>
120      Collector<T, ?, M> toMultimap(
121          java.util.function.Function<? super T, ? extends K> keyFunction,
122          java.util.function.Function<? super T, ? extends V> valueFunction,
123          java.util.function.Supplier<M> multimapSupplier) {
124    return CollectCollectors.<T, K, V, M>toMultimap(keyFunction, valueFunction, multimapSupplier);
125  }
126
127  /**
128   * Returns a {@code Collector} accumulating entries into a {@code Multimap} generated from the
129   * specified supplier. Each input element is mapped to a key and a stream of values, each of which
130   * are put into the resulting {@code Multimap}, in the encounter order of the stream and the
131   * encounter order of the streams of values.
132   *
133   * <p>Example:
134   *
135   * <pre>{@code
136   * static final ListMultimap<Character, Character> FIRST_LETTER_MULTIMAP =
137   *     Stream.of("banana", "apple", "carrot", "asparagus", "cherry")
138   *         .collect(
139   *             flatteningToMultimap(
140   *                  str -> str.charAt(0),
141   *                  str -> str.substring(1).chars().mapToObj(c -> (char) c),
142   *                  MultimapBuilder.linkedHashKeys().arrayListValues()::build));
143   *
144   * // is equivalent to
145   *
146   * static final ListMultimap<Character, Character> FIRST_LETTER_MULTIMAP;
147   *
148   * static {
149   *     FIRST_LETTER_MULTIMAP = MultimapBuilder.linkedHashKeys().arrayListValues().build();
150   *     FIRST_LETTER_MULTIMAP.putAll('b', Arrays.asList('a', 'n', 'a', 'n', 'a'));
151   *     FIRST_LETTER_MULTIMAP.putAll('a', Arrays.asList('p', 'p', 'l', 'e'));
152   *     FIRST_LETTER_MULTIMAP.putAll('c', Arrays.asList('a', 'r', 'r', 'o', 't'));
153   *     FIRST_LETTER_MULTIMAP.putAll('a', Arrays.asList('s', 'p', 'a', 'r', 'a', 'g', 'u', 's'));
154   *     FIRST_LETTER_MULTIMAP.putAll('c', Arrays.asList('h', 'e', 'r', 'r', 'y'));
155   * }
156   * }</pre>
157   *
158   * @since 33.2.0 (available since 21.0 in guava-jre)
159   */
160  @SuppressWarnings("Java7ApiChecker")
161  @IgnoreJRERequirement // Users will use this only if they're already using streams.
162  public static <
163          T extends @Nullable Object,
164          K extends @Nullable Object,
165          V extends @Nullable Object,
166          M extends Multimap<K, V>>
167      Collector<T, ?, M> flatteningToMultimap(
168          java.util.function.Function<? super T, ? extends K> keyFunction,
169          java.util.function.Function<? super T, ? extends Stream<? extends V>> valueFunction,
170          java.util.function.Supplier<M> multimapSupplier) {
171    return CollectCollectors.<T, K, V, M>flatteningToMultimap(
172        keyFunction, valueFunction, multimapSupplier);
173  }
174
175  /**
176   * Creates a new {@code Multimap} backed by {@code map}, whose internal value collections are
177   * generated by {@code factory}.
178   *
179   * <p><b>Warning: do not use</b> this method when the collections returned by {@code factory}
180   * implement either {@link List} or {@code Set}! Use the more specific method {@link
181   * #newListMultimap}, {@link #newSetMultimap} or {@link #newSortedSetMultimap} instead, to avoid
182   * very surprising behavior from {@link Multimap#equals}.
183   *
184   * <p>The {@code factory}-generated and {@code map} classes determine the multimap iteration
185   * order. They also specify the behavior of the {@code equals}, {@code hashCode}, and {@code
186   * toString} methods for the multimap and its returned views. However, the multimap's {@code get}
187   * method returns instances of a different class than {@code factory.get()} does.
188   *
189   * <p>The multimap is serializable if {@code map}, {@code factory}, the collections generated by
190   * {@code factory}, and the multimap contents are all serializable.
191   *
192   * <p>The multimap is not threadsafe when any concurrent operations update the multimap, even if
193   * {@code map} and the instances generated by {@code factory} are. Concurrent read operations will
194   * work correctly. To allow concurrent update operations, wrap the multimap with a call to {@link
195   * #synchronizedMultimap}.
196   *
197   * <p>Call this method only when the simpler methods {@link ArrayListMultimap#create()}, {@link
198   * HashMultimap#create()}, {@link LinkedHashMultimap#create()}, {@link
199   * LinkedListMultimap#create()}, {@link TreeMultimap#create()}, and {@link
200   * TreeMultimap#create(Comparator, Comparator)} won't suffice.
201   *
202   * <p>Note: the multimap assumes complete ownership over of {@code map} and the collections
203   * returned by {@code factory}. Those objects should not be manually updated and they should not
204   * use soft, weak, or phantom references.
205   *
206   * @param map place to store the mapping from each key to its corresponding values
207   * @param factory supplier of new, empty collections that will each hold all values for a given
208   *     key
209   * @throws IllegalArgumentException if {@code map} is not empty
210   */
211  public static <K extends @Nullable Object, V extends @Nullable Object> Multimap<K, V> newMultimap(
212      Map<K, Collection<V>> map, final Supplier<? extends Collection<V>> factory) {
213    return new CustomMultimap<>(map, factory);
214  }
215
216  private static class CustomMultimap<K extends @Nullable Object, V extends @Nullable Object>
217      extends AbstractMapBasedMultimap<K, V> {
218    transient Supplier<? extends Collection<V>> factory;
219
220    CustomMultimap(Map<K, Collection<V>> map, Supplier<? extends Collection<V>> factory) {
221      super(map);
222      this.factory = checkNotNull(factory);
223    }
224
225    @Override
226    Set<K> createKeySet() {
227      return createMaybeNavigableKeySet();
228    }
229
230    @Override
231    Map<K, Collection<V>> createAsMap() {
232      return createMaybeNavigableAsMap();
233    }
234
235    @Override
236    protected Collection<V> createCollection() {
237      return factory.get();
238    }
239
240    @Override
241    <E extends @Nullable Object> Collection<E> unmodifiableCollectionSubclass(
242        Collection<E> collection) {
243      if (collection instanceof NavigableSet) {
244        return Sets.unmodifiableNavigableSet((NavigableSet<E>) collection);
245      } else if (collection instanceof SortedSet) {
246        return Collections.unmodifiableSortedSet((SortedSet<E>) collection);
247      } else if (collection instanceof Set) {
248        return Collections.unmodifiableSet((Set<E>) collection);
249      } else if (collection instanceof List) {
250        return Collections.unmodifiableList((List<E>) collection);
251      } else {
252        return Collections.unmodifiableCollection(collection);
253      }
254    }
255
256    @Override
257    Collection<V> wrapCollection(@ParametricNullness K key, Collection<V> collection) {
258      if (collection instanceof List) {
259        return wrapList(key, (List<V>) collection, null);
260      } else if (collection instanceof NavigableSet) {
261        return new WrappedNavigableSet(key, (NavigableSet<V>) collection, null);
262      } else if (collection instanceof SortedSet) {
263        return new WrappedSortedSet(key, (SortedSet<V>) collection, null);
264      } else if (collection instanceof Set) {
265        return new WrappedSet(key, (Set<V>) collection);
266      } else {
267        return new WrappedCollection(key, collection, null);
268      }
269    }
270
271    // can't use Serialization writeMultimap and populateMultimap methods since
272    // there's no way to generate the empty backing map.
273
274    /**
275     * @serialData the factory and the backing map
276     */
277    @GwtIncompatible // java.io.ObjectOutputStream
278    @J2ktIncompatible
279    private void writeObject(ObjectOutputStream stream) throws IOException {
280      stream.defaultWriteObject();
281      stream.writeObject(factory);
282      stream.writeObject(backingMap());
283    }
284
285    @GwtIncompatible // java.io.ObjectInputStream
286    @J2ktIncompatible
287    @SuppressWarnings("unchecked") // reading data stored by writeObject
288    private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
289      stream.defaultReadObject();
290      factory = (Supplier<? extends Collection<V>>) requireNonNull(stream.readObject());
291      Map<K, Collection<V>> map = (Map<K, Collection<V>>) requireNonNull(stream.readObject());
292      setMap(map);
293    }
294
295    @GwtIncompatible // java serialization not supported
296    @J2ktIncompatible
297    private static final long serialVersionUID = 0;
298  }
299
300  /**
301   * Creates a new {@code ListMultimap} that uses the provided map and factory. It can generate a
302   * multimap based on arbitrary {@link Map} and {@link List} classes.
303   *
304   * <p>The {@code factory}-generated and {@code map} classes determine the multimap iteration
305   * order. They also specify the behavior of the {@code equals}, {@code hashCode}, and {@code
306   * toString} methods for the multimap and its returned views. The multimap's {@code get}, {@code
307   * removeAll}, and {@code replaceValues} methods return {@code RandomAccess} lists if the factory
308   * does. However, the multimap's {@code get} method returns instances of a different class than
309   * does {@code factory.get()}.
310   *
311   * <p>The multimap is serializable if {@code map}, {@code factory}, the lists generated by {@code
312   * factory}, and the multimap contents are all serializable.
313   *
314   * <p>The multimap is not threadsafe when any concurrent operations update the multimap, even if
315   * {@code map} and the instances generated by {@code factory} are. Concurrent read operations will
316   * work correctly. To allow concurrent update operations, wrap the multimap with a call to {@link
317   * #synchronizedListMultimap}.
318   *
319   * <p>Call this method only when the simpler methods {@link ArrayListMultimap#create()} and {@link
320   * LinkedListMultimap#create()} won't suffice.
321   *
322   * <p>Note: the multimap assumes complete ownership over of {@code map} and the lists returned by
323   * {@code factory}. Those objects should not be manually updated, they should be empty when
324   * provided, and they should not use soft, weak, or phantom references.
325   *
326   * @param map place to store the mapping from each key to its corresponding values
327   * @param factory supplier of new, empty lists that will each hold all values for a given key
328   * @throws IllegalArgumentException if {@code map} is not empty
329   */
330  public static <K extends @Nullable Object, V extends @Nullable Object>
331      ListMultimap<K, V> newListMultimap(
332          Map<K, Collection<V>> map, final Supplier<? extends List<V>> factory) {
333    return new CustomListMultimap<>(map, factory);
334  }
335
336  private static class CustomListMultimap<K extends @Nullable Object, V extends @Nullable Object>
337      extends AbstractListMultimap<K, V> {
338    transient Supplier<? extends List<V>> factory;
339
340    CustomListMultimap(Map<K, Collection<V>> map, Supplier<? extends List<V>> factory) {
341      super(map);
342      this.factory = checkNotNull(factory);
343    }
344
345    @Override
346    Set<K> createKeySet() {
347      return createMaybeNavigableKeySet();
348    }
349
350    @Override
351    Map<K, Collection<V>> createAsMap() {
352      return createMaybeNavigableAsMap();
353    }
354
355    @Override
356    protected List<V> createCollection() {
357      return factory.get();
358    }
359
360    /**
361     * @serialData the factory and the backing map
362     */
363    @GwtIncompatible // java.io.ObjectOutputStream
364    @J2ktIncompatible
365    private void writeObject(ObjectOutputStream stream) throws IOException {
366      stream.defaultWriteObject();
367      stream.writeObject(factory);
368      stream.writeObject(backingMap());
369    }
370
371    @GwtIncompatible // java.io.ObjectInputStream
372    @J2ktIncompatible
373    @SuppressWarnings("unchecked") // reading data stored by writeObject
374    private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
375      stream.defaultReadObject();
376      factory = (Supplier<? extends List<V>>) requireNonNull(stream.readObject());
377      Map<K, Collection<V>> map = (Map<K, Collection<V>>) requireNonNull(stream.readObject());
378      setMap(map);
379    }
380
381    @GwtIncompatible // java serialization not supported
382    @J2ktIncompatible
383    private static final long serialVersionUID = 0;
384  }
385
386  /**
387   * Creates a new {@code SetMultimap} that uses the provided map and factory. It can generate a
388   * multimap based on arbitrary {@link Map} and {@link Set} classes.
389   *
390   * <p>The {@code factory}-generated and {@code map} classes determine the multimap iteration
391   * order. They also specify the behavior of the {@code equals}, {@code hashCode}, and {@code
392   * toString} methods for the multimap and its returned views. However, the multimap's {@code get}
393   * method returns instances of a different class than {@code factory.get()} does.
394   *
395   * <p>The multimap is serializable if {@code map}, {@code factory}, the sets generated by {@code
396   * factory}, and the multimap contents are all serializable.
397   *
398   * <p>The multimap is not threadsafe when any concurrent operations update the multimap, even if
399   * {@code map} and the instances generated by {@code factory} are. Concurrent read operations will
400   * work correctly. To allow concurrent update operations, wrap the multimap with a call to {@link
401   * #synchronizedSetMultimap}.
402   *
403   * <p>Call this method only when the simpler methods {@link HashMultimap#create()}, {@link
404   * LinkedHashMultimap#create()}, {@link TreeMultimap#create()}, and {@link
405   * TreeMultimap#create(Comparator, Comparator)} won't suffice.
406   *
407   * <p>Note: the multimap assumes complete ownership over of {@code map} and the sets returned by
408   * {@code factory}. Those objects should not be manually updated and they should not use soft,
409   * weak, or phantom references.
410   *
411   * @param map place to store the mapping from each key to its corresponding values
412   * @param factory supplier of new, empty sets that will each hold all values for a given key
413   * @throws IllegalArgumentException if {@code map} is not empty
414   */
415  public static <K extends @Nullable Object, V extends @Nullable Object>
416      SetMultimap<K, V> newSetMultimap(
417          Map<K, Collection<V>> map, final Supplier<? extends Set<V>> factory) {
418    return new CustomSetMultimap<>(map, factory);
419  }
420
421  private static class CustomSetMultimap<K extends @Nullable Object, V extends @Nullable Object>
422      extends AbstractSetMultimap<K, V> {
423    transient Supplier<? extends Set<V>> factory;
424
425    CustomSetMultimap(Map<K, Collection<V>> map, Supplier<? extends Set<V>> factory) {
426      super(map);
427      this.factory = checkNotNull(factory);
428    }
429
430    @Override
431    Set<K> createKeySet() {
432      return createMaybeNavigableKeySet();
433    }
434
435    @Override
436    Map<K, Collection<V>> createAsMap() {
437      return createMaybeNavigableAsMap();
438    }
439
440    @Override
441    protected Set<V> createCollection() {
442      return factory.get();
443    }
444
445    @Override
446    <E extends @Nullable Object> Collection<E> unmodifiableCollectionSubclass(
447        Collection<E> collection) {
448      if (collection instanceof NavigableSet) {
449        return Sets.unmodifiableNavigableSet((NavigableSet<E>) collection);
450      } else if (collection instanceof SortedSet) {
451        return Collections.unmodifiableSortedSet((SortedSet<E>) collection);
452      } else {
453        return Collections.unmodifiableSet((Set<E>) collection);
454      }
455    }
456
457    @Override
458    Collection<V> wrapCollection(@ParametricNullness K key, Collection<V> collection) {
459      if (collection instanceof NavigableSet) {
460        return new WrappedNavigableSet(key, (NavigableSet<V>) collection, null);
461      } else if (collection instanceof SortedSet) {
462        return new WrappedSortedSet(key, (SortedSet<V>) collection, null);
463      } else {
464        return new WrappedSet(key, (Set<V>) collection);
465      }
466    }
467
468    /**
469     * @serialData the factory and the backing map
470     */
471    @GwtIncompatible // java.io.ObjectOutputStream
472    @J2ktIncompatible
473    private void writeObject(ObjectOutputStream stream) throws IOException {
474      stream.defaultWriteObject();
475      stream.writeObject(factory);
476      stream.writeObject(backingMap());
477    }
478
479    @GwtIncompatible // java.io.ObjectInputStream
480    @J2ktIncompatible
481    @SuppressWarnings("unchecked") // reading data stored by writeObject
482    private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
483      stream.defaultReadObject();
484      factory = (Supplier<? extends Set<V>>) requireNonNull(stream.readObject());
485      Map<K, Collection<V>> map = (Map<K, Collection<V>>) requireNonNull(stream.readObject());
486      setMap(map);
487    }
488
489    @GwtIncompatible // not needed in emulated source
490    @J2ktIncompatible
491    private static final long serialVersionUID = 0;
492  }
493
494  /**
495   * Creates a new {@code SortedSetMultimap} that uses the provided map and factory. It can generate
496   * a multimap based on arbitrary {@link Map} and {@link SortedSet} classes.
497   *
498   * <p>The {@code factory}-generated and {@code map} classes determine the multimap iteration
499   * order. They also specify the behavior of the {@code equals}, {@code hashCode}, and {@code
500   * toString} methods for the multimap and its returned views. However, the multimap's {@code get}
501   * method returns instances of a different class than {@code factory.get()} does.
502   *
503   * <p>The multimap is serializable if {@code map}, {@code factory}, the sets generated by {@code
504   * factory}, and the multimap contents are all serializable.
505   *
506   * <p>The multimap is not threadsafe when any concurrent operations update the multimap, even if
507   * {@code map} and the instances generated by {@code factory} are. Concurrent read operations will
508   * work correctly. To allow concurrent update operations, wrap the multimap with a call to {@link
509   * #synchronizedSortedSetMultimap}.
510   *
511   * <p>Call this method only when the simpler methods {@link TreeMultimap#create()} and {@link
512   * TreeMultimap#create(Comparator, Comparator)} won't suffice.
513   *
514   * <p>Note: the multimap assumes complete ownership over of {@code map} and the sets returned by
515   * {@code factory}. Those objects should not be manually updated and they should not use soft,
516   * weak, or phantom references.
517   *
518   * @param map place to store the mapping from each key to its corresponding values
519   * @param factory supplier of new, empty sorted sets that will each hold all values for a given
520   *     key
521   * @throws IllegalArgumentException if {@code map} is not empty
522   */
523  public static <K extends @Nullable Object, V extends @Nullable Object>
524      SortedSetMultimap<K, V> newSortedSetMultimap(
525          Map<K, Collection<V>> map, final Supplier<? extends SortedSet<V>> factory) {
526    return new CustomSortedSetMultimap<>(map, factory);
527  }
528
529  private static class CustomSortedSetMultimap<
530          K extends @Nullable Object, V extends @Nullable Object>
531      extends AbstractSortedSetMultimap<K, V> {
532    transient Supplier<? extends SortedSet<V>> factory;
533    @CheckForNull transient Comparator<? super V> valueComparator;
534
535    CustomSortedSetMultimap(Map<K, Collection<V>> map, Supplier<? extends SortedSet<V>> factory) {
536      super(map);
537      this.factory = checkNotNull(factory);
538      valueComparator = factory.get().comparator();
539    }
540
541    @Override
542    Set<K> createKeySet() {
543      return createMaybeNavigableKeySet();
544    }
545
546    @Override
547    Map<K, Collection<V>> createAsMap() {
548      return createMaybeNavigableAsMap();
549    }
550
551    @Override
552    protected SortedSet<V> createCollection() {
553      return factory.get();
554    }
555
556    @Override
557    @CheckForNull
558    public Comparator<? super V> valueComparator() {
559      return valueComparator;
560    }
561
562    /**
563     * @serialData the factory and the backing map
564     */
565    @GwtIncompatible // java.io.ObjectOutputStream
566    @J2ktIncompatible
567    private void writeObject(ObjectOutputStream stream) throws IOException {
568      stream.defaultWriteObject();
569      stream.writeObject(factory);
570      stream.writeObject(backingMap());
571    }
572
573    @GwtIncompatible // java.io.ObjectInputStream
574    @J2ktIncompatible
575    @SuppressWarnings("unchecked") // reading data stored by writeObject
576    private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
577      stream.defaultReadObject();
578      factory = (Supplier<? extends SortedSet<V>>) requireNonNull(stream.readObject());
579      valueComparator = factory.get().comparator();
580      Map<K, Collection<V>> map = (Map<K, Collection<V>>) requireNonNull(stream.readObject());
581      setMap(map);
582    }
583
584    @GwtIncompatible // not needed in emulated source
585    @J2ktIncompatible
586    private static final long serialVersionUID = 0;
587  }
588
589  /**
590   * Copies each key-value mapping in {@code source} into {@code dest}, with its key and value
591   * reversed.
592   *
593   * <p>If {@code source} is an {@link ImmutableMultimap}, consider using {@link
594   * ImmutableMultimap#inverse} instead.
595   *
596   * @param source any multimap
597   * @param dest the multimap to copy into; usually empty
598   * @return {@code dest}
599   */
600  @CanIgnoreReturnValue
601  public static <K extends @Nullable Object, V extends @Nullable Object, M extends Multimap<K, V>>
602      M invertFrom(Multimap<? extends V, ? extends K> source, M dest) {
603    checkNotNull(dest);
604    for (Map.Entry<? extends V, ? extends K> entry : source.entries()) {
605      dest.put(entry.getValue(), entry.getKey());
606    }
607    return dest;
608  }
609
610  /**
611   * Returns a synchronized (thread-safe) multimap backed by the specified multimap. In order to
612   * guarantee serial access, it is critical that <b>all</b> access to the backing multimap is
613   * accomplished through the returned multimap.
614   *
615   * <p>It is imperative that the user manually synchronize on the returned multimap when accessing
616   * any of its collection views:
617   *
618   * <pre>{@code
619   * Multimap<K, V> multimap = Multimaps.synchronizedMultimap(
620   *     HashMultimap.<K, V>create());
621   * ...
622   * Collection<V> values = multimap.get(key);  // Needn't be in synchronized block
623   * ...
624   * synchronized (multimap) {  // Synchronizing on multimap, not values!
625   *   Iterator<V> i = values.iterator(); // Must be in synchronized block
626   *   while (i.hasNext()) {
627   *     foo(i.next());
628   *   }
629   * }
630   * }</pre>
631   *
632   * <p>Failure to follow this advice may result in non-deterministic behavior.
633   *
634   * <p>Note that the generated multimap's {@link Multimap#removeAll} and {@link
635   * Multimap#replaceValues} methods return collections that aren't synchronized.
636   *
637   * <p>The returned multimap will be serializable if the specified multimap is serializable.
638   *
639   * @param multimap the multimap to be wrapped in a synchronized view
640   * @return a synchronized view of the specified multimap
641   */
642  @J2ktIncompatible // Synchronized
643  public static <K extends @Nullable Object, V extends @Nullable Object>
644      Multimap<K, V> synchronizedMultimap(Multimap<K, V> multimap) {
645    return Synchronized.multimap(multimap, null);
646  }
647
648  /**
649   * Returns an unmodifiable view of the specified multimap. Query operations on the returned
650   * multimap "read through" to the specified multimap, and attempts to modify the returned
651   * multimap, either directly or through the multimap's views, result in an {@code
652   * UnsupportedOperationException}.
653   *
654   * <p>The returned multimap will be serializable if the specified multimap is serializable.
655   *
656   * @param delegate the multimap for which an unmodifiable view is to be returned
657   * @return an unmodifiable view of the specified multimap
658   */
659  public static <K extends @Nullable Object, V extends @Nullable Object>
660      Multimap<K, V> unmodifiableMultimap(Multimap<K, V> delegate) {
661    if (delegate instanceof UnmodifiableMultimap || delegate instanceof ImmutableMultimap) {
662      return delegate;
663    }
664    return new UnmodifiableMultimap<>(delegate);
665  }
666
667  /**
668   * Simply returns its argument.
669   *
670   * @deprecated no need to use this
671   * @since 10.0
672   */
673  @Deprecated
674  public static <K, V> Multimap<K, V> unmodifiableMultimap(ImmutableMultimap<K, V> delegate) {
675    return checkNotNull(delegate);
676  }
677
678  private static class UnmodifiableMultimap<K extends @Nullable Object, V extends @Nullable Object>
679      extends ForwardingMultimap<K, V> implements Serializable {
680    final Multimap<K, V> delegate;
681    @LazyInit @CheckForNull transient Collection<Entry<K, V>> entries;
682    @LazyInit @CheckForNull transient Multiset<K> keys;
683    @LazyInit @CheckForNull transient Set<K> keySet;
684    @LazyInit @CheckForNull transient Collection<V> values;
685    @LazyInit @CheckForNull transient Map<K, Collection<V>> map;
686
687    UnmodifiableMultimap(final Multimap<K, V> delegate) {
688      this.delegate = checkNotNull(delegate);
689    }
690
691    @Override
692    protected Multimap<K, V> delegate() {
693      return delegate;
694    }
695
696    @Override
697    public void clear() {
698      throw new UnsupportedOperationException();
699    }
700
701    @Override
702    public Map<K, Collection<V>> asMap() {
703      Map<K, Collection<V>> result = map;
704      if (result == null) {
705        result =
706            map =
707                Collections.unmodifiableMap(
708                    Maps.transformValues(
709                        delegate.asMap(), collection -> unmodifiableValueCollection(collection)));
710      }
711      return result;
712    }
713
714    @Override
715    public Collection<Entry<K, V>> entries() {
716      Collection<Entry<K, V>> result = entries;
717      if (result == null) {
718        entries = result = unmodifiableEntries(delegate.entries());
719      }
720      return result;
721    }
722
723    @Override
724    public Collection<V> get(@ParametricNullness K key) {
725      return unmodifiableValueCollection(delegate.get(key));
726    }
727
728    @Override
729    public Multiset<K> keys() {
730      Multiset<K> result = keys;
731      if (result == null) {
732        keys = result = Multisets.unmodifiableMultiset(delegate.keys());
733      }
734      return result;
735    }
736
737    @Override
738    public Set<K> keySet() {
739      Set<K> result = keySet;
740      if (result == null) {
741        keySet = result = Collections.unmodifiableSet(delegate.keySet());
742      }
743      return result;
744    }
745
746    @Override
747    public boolean put(@ParametricNullness K key, @ParametricNullness V value) {
748      throw new UnsupportedOperationException();
749    }
750
751    @Override
752    public boolean putAll(@ParametricNullness K key, Iterable<? extends V> values) {
753      throw new UnsupportedOperationException();
754    }
755
756    @Override
757    public boolean putAll(Multimap<? extends K, ? extends V> multimap) {
758      throw new UnsupportedOperationException();
759    }
760
761    @Override
762    public boolean remove(@CheckForNull Object key, @CheckForNull Object value) {
763      throw new UnsupportedOperationException();
764    }
765
766    @Override
767    public Collection<V> removeAll(@CheckForNull Object key) {
768      throw new UnsupportedOperationException();
769    }
770
771    @Override
772    public Collection<V> replaceValues(@ParametricNullness K key, Iterable<? extends V> values) {
773      throw new UnsupportedOperationException();
774    }
775
776    @Override
777    public Collection<V> values() {
778      Collection<V> result = values;
779      if (result == null) {
780        values = result = Collections.unmodifiableCollection(delegate.values());
781      }
782      return result;
783    }
784
785    private static final long serialVersionUID = 0;
786  }
787
788  private static class UnmodifiableListMultimap<
789          K extends @Nullable Object, V extends @Nullable Object>
790      extends UnmodifiableMultimap<K, V> implements ListMultimap<K, V> {
791    UnmodifiableListMultimap(ListMultimap<K, V> delegate) {
792      super(delegate);
793    }
794
795    @Override
796    public ListMultimap<K, V> delegate() {
797      return (ListMultimap<K, V>) super.delegate();
798    }
799
800    @Override
801    public List<V> get(@ParametricNullness K key) {
802      return Collections.unmodifiableList(delegate().get(key));
803    }
804
805    @Override
806    public List<V> removeAll(@CheckForNull Object key) {
807      throw new UnsupportedOperationException();
808    }
809
810    @Override
811    public List<V> replaceValues(@ParametricNullness K key, Iterable<? extends V> values) {
812      throw new UnsupportedOperationException();
813    }
814
815    private static final long serialVersionUID = 0;
816  }
817
818  private static class UnmodifiableSetMultimap<
819          K extends @Nullable Object, V extends @Nullable Object>
820      extends UnmodifiableMultimap<K, V> implements SetMultimap<K, V> {
821    UnmodifiableSetMultimap(SetMultimap<K, V> delegate) {
822      super(delegate);
823    }
824
825    @Override
826    public SetMultimap<K, V> delegate() {
827      return (SetMultimap<K, V>) super.delegate();
828    }
829
830    @Override
831    public Set<V> get(@ParametricNullness K key) {
832      /*
833       * Note that this doesn't return a SortedSet when delegate is a
834       * SortedSetMultiset, unlike (SortedSet<V>) super.get().
835       */
836      return Collections.unmodifiableSet(delegate().get(key));
837    }
838
839    @Override
840    public Set<Map.Entry<K, V>> entries() {
841      return Maps.unmodifiableEntrySet(delegate().entries());
842    }
843
844    @Override
845    public Set<V> removeAll(@CheckForNull Object key) {
846      throw new UnsupportedOperationException();
847    }
848
849    @Override
850    public Set<V> replaceValues(@ParametricNullness K key, Iterable<? extends V> values) {
851      throw new UnsupportedOperationException();
852    }
853
854    private static final long serialVersionUID = 0;
855  }
856
857  private static class UnmodifiableSortedSetMultimap<
858          K extends @Nullable Object, V extends @Nullable Object>
859      extends UnmodifiableSetMultimap<K, V> implements SortedSetMultimap<K, V> {
860    UnmodifiableSortedSetMultimap(SortedSetMultimap<K, V> delegate) {
861      super(delegate);
862    }
863
864    @Override
865    public SortedSetMultimap<K, V> delegate() {
866      return (SortedSetMultimap<K, V>) super.delegate();
867    }
868
869    @Override
870    public SortedSet<V> get(@ParametricNullness K key) {
871      return Collections.unmodifiableSortedSet(delegate().get(key));
872    }
873
874    @Override
875    public SortedSet<V> removeAll(@CheckForNull Object key) {
876      throw new UnsupportedOperationException();
877    }
878
879    @Override
880    public SortedSet<V> replaceValues(@ParametricNullness K key, Iterable<? extends V> values) {
881      throw new UnsupportedOperationException();
882    }
883
884    @Override
885    @CheckForNull
886    public Comparator<? super V> valueComparator() {
887      return delegate().valueComparator();
888    }
889
890    private static final long serialVersionUID = 0;
891  }
892
893  /**
894   * Returns a synchronized (thread-safe) {@code SetMultimap} backed by the specified multimap.
895   *
896   * <p>You must follow the warnings described in {@link #synchronizedMultimap}.
897   *
898   * <p>The returned multimap will be serializable if the specified multimap is serializable.
899   *
900   * @param multimap the multimap to be wrapped
901   * @return a synchronized view of the specified multimap
902   */
903  @J2ktIncompatible // Synchronized
904  public static <K extends @Nullable Object, V extends @Nullable Object>
905      SetMultimap<K, V> synchronizedSetMultimap(SetMultimap<K, V> multimap) {
906    return Synchronized.setMultimap(multimap, null);
907  }
908
909  /**
910   * Returns an unmodifiable view of the specified {@code SetMultimap}. Query operations on the
911   * returned multimap "read through" to the specified multimap, and attempts to modify the returned
912   * multimap, either directly or through the multimap's views, result in an {@code
913   * UnsupportedOperationException}.
914   *
915   * <p>The returned multimap will be serializable if the specified multimap is serializable.
916   *
917   * @param delegate the multimap for which an unmodifiable view is to be returned
918   * @return an unmodifiable view of the specified multimap
919   */
920  public static <K extends @Nullable Object, V extends @Nullable Object>
921      SetMultimap<K, V> unmodifiableSetMultimap(SetMultimap<K, V> delegate) {
922    if (delegate instanceof UnmodifiableSetMultimap || delegate instanceof ImmutableSetMultimap) {
923      return delegate;
924    }
925    return new UnmodifiableSetMultimap<>(delegate);
926  }
927
928  /**
929   * Simply returns its argument.
930   *
931   * @deprecated no need to use this
932   * @since 10.0
933   */
934  @Deprecated
935  public static <K, V> SetMultimap<K, V> unmodifiableSetMultimap(
936      ImmutableSetMultimap<K, V> delegate) {
937    return checkNotNull(delegate);
938  }
939
940  /**
941   * Returns a synchronized (thread-safe) {@code SortedSetMultimap} backed by the specified
942   * multimap.
943   *
944   * <p>You must follow the warnings described in {@link #synchronizedMultimap}.
945   *
946   * <p>The returned multimap will be serializable if the specified multimap is serializable.
947   *
948   * @param multimap the multimap to be wrapped
949   * @return a synchronized view of the specified multimap
950   */
951  @J2ktIncompatible // Synchronized
952  public static <K extends @Nullable Object, V extends @Nullable Object>
953      SortedSetMultimap<K, V> synchronizedSortedSetMultimap(SortedSetMultimap<K, V> multimap) {
954    return Synchronized.sortedSetMultimap(multimap, null);
955  }
956
957  /**
958   * Returns an unmodifiable view of the specified {@code SortedSetMultimap}. Query operations on
959   * the returned multimap "read through" to the specified multimap, and attempts to modify the
960   * returned multimap, either directly or through the multimap's views, result in an {@code
961   * UnsupportedOperationException}.
962   *
963   * <p>The returned multimap will be serializable if the specified multimap is serializable.
964   *
965   * @param delegate the multimap for which an unmodifiable view is to be returned
966   * @return an unmodifiable view of the specified multimap
967   */
968  public static <K extends @Nullable Object, V extends @Nullable Object>
969      SortedSetMultimap<K, V> unmodifiableSortedSetMultimap(SortedSetMultimap<K, V> delegate) {
970    if (delegate instanceof UnmodifiableSortedSetMultimap) {
971      return delegate;
972    }
973    return new UnmodifiableSortedSetMultimap<>(delegate);
974  }
975
976  /**
977   * Returns a synchronized (thread-safe) {@code ListMultimap} backed by the specified multimap.
978   *
979   * <p>You must follow the warnings described in {@link #synchronizedMultimap}.
980   *
981   * @param multimap the multimap to be wrapped
982   * @return a synchronized view of the specified multimap
983   */
984  @J2ktIncompatible // Synchronized
985  public static <K extends @Nullable Object, V extends @Nullable Object>
986      ListMultimap<K, V> synchronizedListMultimap(ListMultimap<K, V> multimap) {
987    return Synchronized.listMultimap(multimap, null);
988  }
989
990  /**
991   * Returns an unmodifiable view of the specified {@code ListMultimap}. Query operations on the
992   * returned multimap "read through" to the specified multimap, and attempts to modify the returned
993   * multimap, either directly or through the multimap's views, result in an {@code
994   * UnsupportedOperationException}.
995   *
996   * <p>The returned multimap will be serializable if the specified multimap is serializable.
997   *
998   * @param delegate the multimap for which an unmodifiable view is to be returned
999   * @return an unmodifiable view of the specified multimap
1000   */
1001  public static <K extends @Nullable Object, V extends @Nullable Object>
1002      ListMultimap<K, V> unmodifiableListMultimap(ListMultimap<K, V> delegate) {
1003    if (delegate instanceof UnmodifiableListMultimap || delegate instanceof ImmutableListMultimap) {
1004      return delegate;
1005    }
1006    return new UnmodifiableListMultimap<>(delegate);
1007  }
1008
1009  /**
1010   * Simply returns its argument.
1011   *
1012   * @deprecated no need to use this
1013   * @since 10.0
1014   */
1015  @Deprecated
1016  public static <K, V> ListMultimap<K, V> unmodifiableListMultimap(
1017      ImmutableListMultimap<K, V> delegate) {
1018    return checkNotNull(delegate);
1019  }
1020
1021  /**
1022   * Returns an unmodifiable view of the specified collection, preserving the interface for
1023   * instances of {@code SortedSet}, {@code Set}, {@code List} and {@code Collection}, in that order
1024   * of preference.
1025   *
1026   * @param collection the collection for which to return an unmodifiable view
1027   * @return an unmodifiable view of the collection
1028   */
1029  private static <V extends @Nullable Object> Collection<V> unmodifiableValueCollection(
1030      Collection<V> collection) {
1031    if (collection instanceof SortedSet) {
1032      return Collections.unmodifiableSortedSet((SortedSet<V>) collection);
1033    } else if (collection instanceof Set) {
1034      return Collections.unmodifiableSet((Set<V>) collection);
1035    } else if (collection instanceof List) {
1036      return Collections.unmodifiableList((List<V>) collection);
1037    }
1038    return Collections.unmodifiableCollection(collection);
1039  }
1040
1041  /**
1042   * Returns an unmodifiable view of the specified collection of entries. The {@link Entry#setValue}
1043   * operation throws an {@link UnsupportedOperationException}. If the specified collection is a
1044   * {@code Set}, the returned collection is also a {@code Set}.
1045   *
1046   * @param entries the entries for which to return an unmodifiable view
1047   * @return an unmodifiable view of the entries
1048   */
1049  private static <K extends @Nullable Object, V extends @Nullable Object>
1050      Collection<Entry<K, V>> unmodifiableEntries(Collection<Entry<K, V>> entries) {
1051    if (entries instanceof Set) {
1052      return Maps.unmodifiableEntrySet((Set<Entry<K, V>>) entries);
1053    }
1054    return new Maps.UnmodifiableEntries<>(Collections.unmodifiableCollection(entries));
1055  }
1056
1057  /**
1058   * Returns {@link ListMultimap#asMap multimap.asMap()}, with its type corrected from {@code Map<K,
1059   * Collection<V>>} to {@code Map<K, List<V>>}.
1060   *
1061   * @since 15.0
1062   */
1063  @SuppressWarnings("unchecked")
1064  // safe by specification of ListMultimap.asMap()
1065  public static <K extends @Nullable Object, V extends @Nullable Object> Map<K, List<V>> asMap(
1066      ListMultimap<K, V> multimap) {
1067    return (Map<K, List<V>>) (Map<K, ?>) multimap.asMap();
1068  }
1069
1070  /**
1071   * Returns {@link SetMultimap#asMap multimap.asMap()}, with its type corrected from {@code Map<K,
1072   * Collection<V>>} to {@code Map<K, Set<V>>}.
1073   *
1074   * @since 15.0
1075   */
1076  @SuppressWarnings("unchecked")
1077  // safe by specification of SetMultimap.asMap()
1078  public static <K extends @Nullable Object, V extends @Nullable Object> Map<K, Set<V>> asMap(
1079      SetMultimap<K, V> multimap) {
1080    return (Map<K, Set<V>>) (Map<K, ?>) multimap.asMap();
1081  }
1082
1083  /**
1084   * Returns {@link SortedSetMultimap#asMap multimap.asMap()}, with its type corrected from {@code
1085   * Map<K, Collection<V>>} to {@code Map<K, SortedSet<V>>}.
1086   *
1087   * @since 15.0
1088   */
1089  @SuppressWarnings("unchecked")
1090  // safe by specification of SortedSetMultimap.asMap()
1091  public static <K extends @Nullable Object, V extends @Nullable Object> Map<K, SortedSet<V>> asMap(
1092      SortedSetMultimap<K, V> multimap) {
1093    return (Map<K, SortedSet<V>>) (Map<K, ?>) multimap.asMap();
1094  }
1095
1096  /**
1097   * Returns {@link Multimap#asMap multimap.asMap()}. This is provided for parity with the other
1098   * more strongly-typed {@code asMap()} implementations.
1099   *
1100   * @since 15.0
1101   */
1102  public static <K extends @Nullable Object, V extends @Nullable Object>
1103      Map<K, Collection<V>> asMap(Multimap<K, V> multimap) {
1104    return multimap.asMap();
1105  }
1106
1107  /**
1108   * Returns a multimap view of the specified map. The multimap is backed by the map, so changes to
1109   * the map are reflected in the multimap, and vice versa. If the map is modified while an
1110   * iteration over one of the multimap's collection views is in progress (except through the
1111   * iterator's own {@code remove} operation, or through the {@code setValue} operation on a map
1112   * entry returned by the iterator), the results of the iteration are undefined.
1113   *
1114   * <p>The multimap supports mapping removal, which removes the corresponding mapping from the map.
1115   * It does not support any operations which might add mappings, such as {@code put}, {@code
1116   * putAll} or {@code replaceValues}.
1117   *
1118   * <p>The returned multimap will be serializable if the specified map is serializable.
1119   *
1120   * @param map the backing map for the returned multimap view
1121   */
1122  public static <K extends @Nullable Object, V extends @Nullable Object> SetMultimap<K, V> forMap(
1123      Map<K, V> map) {
1124    return new MapMultimap<>(map);
1125  }
1126
1127  /** @see Multimaps#forMap */
1128  private static class MapMultimap<K extends @Nullable Object, V extends @Nullable Object>
1129      extends AbstractMultimap<K, V> implements SetMultimap<K, V>, Serializable {
1130    final Map<K, V> map;
1131
1132    MapMultimap(Map<K, V> map) {
1133      this.map = checkNotNull(map);
1134    }
1135
1136    @Override
1137    public int size() {
1138      return map.size();
1139    }
1140
1141    @Override
1142    public boolean containsKey(@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    int distinctElements() {
1757      return multimap.asMap().size();
1758    }
1759
1760    @Override
1761    public int size() {
1762      return multimap.size();
1763    }
1764
1765    @Override
1766    public boolean contains(@CheckForNull Object element) {
1767      return multimap.containsKey(element);
1768    }
1769
1770    @Override
1771    public Iterator<K> iterator() {
1772      return Maps.keyIterator(multimap.entries().iterator());
1773    }
1774
1775    @Override
1776    public int count(@CheckForNull Object element) {
1777      Collection<V> values = Maps.safeGet(multimap.asMap(), element);
1778      return (values == null) ? 0 : values.size();
1779    }
1780
1781    @Override
1782    public int remove(@CheckForNull Object element, int occurrences) {
1783      checkNonnegative(occurrences, "occurrences");
1784      if (occurrences == 0) {
1785        return count(element);
1786      }
1787
1788      Collection<V> values = Maps.safeGet(multimap.asMap(), element);
1789
1790      if (values == null) {
1791        return 0;
1792      }
1793
1794      int oldCount = values.size();
1795      if (occurrences >= oldCount) {
1796        values.clear();
1797      } else {
1798        Iterator<V> iterator = values.iterator();
1799        for (int i = 0; i < occurrences; i++) {
1800          iterator.next();
1801          iterator.remove();
1802        }
1803      }
1804      return oldCount;
1805    }
1806
1807    @Override
1808    public void clear() {
1809      multimap.clear();
1810    }
1811
1812    @Override
1813    public Set<K> elementSet() {
1814      return multimap.keySet();
1815    }
1816
1817    @Override
1818    Iterator<K> elementIterator() {
1819      throw new AssertionError("should never be called");
1820    }
1821  }
1822
1823  /** A skeleton implementation of {@link Multimap#entries()}. */
1824  abstract static class Entries<K extends @Nullable Object, V extends @Nullable Object>
1825      extends AbstractCollection<Map.Entry<K, V>> {
1826    abstract Multimap<K, V> multimap();
1827
1828    @Override
1829    public int size() {
1830      return multimap().size();
1831    }
1832
1833    @Override
1834    public boolean contains(@CheckForNull Object o) {
1835      if (o instanceof Map.Entry) {
1836        Map.Entry<?, ?> entry = (Map.Entry<?, ?>) o;
1837        return multimap().containsEntry(entry.getKey(), entry.getValue());
1838      }
1839      return false;
1840    }
1841
1842    @Override
1843    public boolean remove(@CheckForNull Object o) {
1844      if (o instanceof Map.Entry) {
1845        Map.Entry<?, ?> entry = (Map.Entry<?, ?>) o;
1846        return multimap().remove(entry.getKey(), entry.getValue());
1847      }
1848      return false;
1849    }
1850
1851    @Override
1852    public void clear() {
1853      multimap().clear();
1854    }
1855  }
1856
1857  /** A skeleton implementation of {@link Multimap#asMap()}. */
1858  static final class AsMap<K extends @Nullable Object, V extends @Nullable Object>
1859      extends Maps.ViewCachingAbstractMap<K, Collection<V>> {
1860    @Weak private final Multimap<K, V> multimap;
1861
1862    AsMap(Multimap<K, V> multimap) {
1863      this.multimap = checkNotNull(multimap);
1864    }
1865
1866    @Override
1867    public int size() {
1868      return multimap.keySet().size();
1869    }
1870
1871    @Override
1872    protected Set<Entry<K, Collection<V>>> createEntrySet() {
1873      return new EntrySet();
1874    }
1875
1876    void removeValuesForKey(@CheckForNull Object key) {
1877      multimap.keySet().remove(key);
1878    }
1879
1880    @WeakOuter
1881    class EntrySet extends Maps.EntrySet<K, Collection<V>> {
1882      @Override
1883      Map<K, Collection<V>> map() {
1884        return AsMap.this;
1885      }
1886
1887      @Override
1888      public Iterator<Entry<K, Collection<V>>> iterator() {
1889        return Maps.asMapEntryIterator(multimap.keySet(), key -> multimap.get(key));
1890      }
1891
1892      @Override
1893      public boolean remove(@CheckForNull Object o) {
1894        if (!contains(o)) {
1895          return false;
1896        }
1897        // requireNonNull is safe because of the contains check.
1898        Map.Entry<?, ?> entry = requireNonNull((Map.Entry<?, ?>) o);
1899        removeValuesForKey(entry.getKey());
1900        return true;
1901      }
1902    }
1903
1904    @SuppressWarnings("unchecked")
1905    @Override
1906    @CheckForNull
1907    public Collection<V> get(@CheckForNull Object key) {
1908      return containsKey(key) ? multimap.get((K) key) : null;
1909    }
1910
1911    @Override
1912    @CheckForNull
1913    public Collection<V> remove(@CheckForNull Object key) {
1914      return containsKey(key) ? multimap.removeAll(key) : null;
1915    }
1916
1917    @Override
1918    public Set<K> keySet() {
1919      return multimap.keySet();
1920    }
1921
1922    @Override
1923    public boolean isEmpty() {
1924      return multimap.isEmpty();
1925    }
1926
1927    @Override
1928    public boolean containsKey(@CheckForNull Object key) {
1929      return multimap.containsKey(key);
1930    }
1931
1932    @Override
1933    public void clear() {
1934      multimap.clear();
1935    }
1936  }
1937
1938  /**
1939   * Returns a multimap containing the mappings in {@code unfiltered} whose keys satisfy a
1940   * predicate. The returned multimap is a live view of {@code unfiltered}; changes to one affect
1941   * the other.
1942   *
1943   * <p>The resulting multimap's views have iterators that don't support {@code remove()}, but all
1944   * other methods are supported by the multimap and its views. When adding a key that doesn't
1945   * satisfy the predicate, the multimap's {@code put()}, {@code putAll()}, and {@code
1946   * replaceValues()} methods throw an {@link IllegalArgumentException}.
1947   *
1948   * <p>When methods such as {@code removeAll()} and {@code clear()} are called on the filtered
1949   * multimap or its views, only mappings whose keys satisfy the filter will be removed from the
1950   * underlying multimap.
1951   *
1952   * <p>The returned multimap isn't threadsafe or serializable, even if {@code unfiltered} is.
1953   *
1954   * <p>Many of the filtered multimap's methods, such as {@code size()}, iterate across every
1955   * key/value mapping in the underlying multimap and determine which satisfy the filter. When a
1956   * live view is <i>not</i> needed, it may be faster to copy the filtered multimap and use the
1957   * copy.
1958   *
1959   * <p><b>Warning:</b> {@code keyPredicate} must be <i>consistent with equals</i>, as documented at
1960   * {@link Predicate#apply}. Do not provide a predicate such as {@code
1961   * Predicates.instanceOf(ArrayList.class)}, which is inconsistent with equals.
1962   *
1963   * @since 11.0
1964   */
1965  public static <K extends @Nullable Object, V extends @Nullable Object> Multimap<K, V> filterKeys(
1966      Multimap<K, V> unfiltered, final Predicate<? super K> keyPredicate) {
1967    if (unfiltered instanceof SetMultimap) {
1968      return filterKeys((SetMultimap<K, V>) unfiltered, keyPredicate);
1969    } else if (unfiltered instanceof ListMultimap) {
1970      return filterKeys((ListMultimap<K, V>) unfiltered, keyPredicate);
1971    } else if (unfiltered instanceof FilteredKeyMultimap) {
1972      FilteredKeyMultimap<K, V> prev = (FilteredKeyMultimap<K, V>) unfiltered;
1973      return new FilteredKeyMultimap<>(
1974          prev.unfiltered, Predicates.<K>and(prev.keyPredicate, keyPredicate));
1975    } else if (unfiltered instanceof FilteredMultimap) {
1976      FilteredMultimap<K, V> prev = (FilteredMultimap<K, V>) unfiltered;
1977      return filterFiltered(prev, Maps.<K>keyPredicateOnEntries(keyPredicate));
1978    } else {
1979      return new FilteredKeyMultimap<>(unfiltered, keyPredicate);
1980    }
1981  }
1982
1983  /**
1984   * Returns a multimap containing the mappings in {@code unfiltered} whose keys satisfy a
1985   * predicate. The returned multimap is a live view of {@code unfiltered}; changes to one affect
1986   * the other.
1987   *
1988   * <p>The resulting multimap's views have iterators that don't support {@code remove()}, but all
1989   * other methods are supported by the multimap and its views. When adding a key that doesn't
1990   * satisfy the predicate, the multimap's {@code put()}, {@code putAll()}, and {@code
1991   * replaceValues()} methods throw an {@link IllegalArgumentException}.
1992   *
1993   * <p>When methods such as {@code removeAll()} and {@code clear()} are called on the filtered
1994   * multimap or its views, only mappings whose keys satisfy the filter will be removed from the
1995   * underlying multimap.
1996   *
1997   * <p>The returned multimap isn't threadsafe or serializable, even if {@code unfiltered} is.
1998   *
1999   * <p>Many of the filtered multimap's methods, such as {@code size()}, iterate across every
2000   * key/value mapping in the underlying multimap and determine which satisfy the filter. When a
2001   * live view is <i>not</i> needed, it may be faster to copy the filtered multimap and use the
2002   * copy.
2003   *
2004   * <p><b>Warning:</b> {@code keyPredicate} must be <i>consistent with equals</i>, as documented at
2005   * {@link Predicate#apply}. Do not provide a predicate such as {@code
2006   * Predicates.instanceOf(ArrayList.class)}, which is inconsistent with equals.
2007   *
2008   * @since 14.0
2009   */
2010  public static <K extends @Nullable Object, V extends @Nullable Object>
2011      SetMultimap<K, V> filterKeys(
2012          SetMultimap<K, V> unfiltered, final Predicate<? super K> keyPredicate) {
2013    if (unfiltered instanceof FilteredKeySetMultimap) {
2014      FilteredKeySetMultimap<K, V> prev = (FilteredKeySetMultimap<K, V>) unfiltered;
2015      return new FilteredKeySetMultimap<>(
2016          prev.unfiltered(), Predicates.<K>and(prev.keyPredicate, keyPredicate));
2017    } else if (unfiltered instanceof FilteredSetMultimap) {
2018      FilteredSetMultimap<K, V> prev = (FilteredSetMultimap<K, V>) unfiltered;
2019      return filterFiltered(prev, Maps.<K>keyPredicateOnEntries(keyPredicate));
2020    } else {
2021      return new FilteredKeySetMultimap<>(unfiltered, keyPredicate);
2022    }
2023  }
2024
2025  /**
2026   * Returns a multimap containing the mappings in {@code unfiltered} whose keys satisfy a
2027   * predicate. The returned multimap is a live view of {@code unfiltered}; changes to one affect
2028   * the other.
2029   *
2030   * <p>The resulting multimap's views have iterators that don't support {@code remove()}, but all
2031   * other methods are supported by the multimap and its views. When adding a key that doesn't
2032   * satisfy the predicate, the multimap's {@code put()}, {@code putAll()}, and {@code
2033   * replaceValues()} methods throw an {@link IllegalArgumentException}.
2034   *
2035   * <p>When methods such as {@code removeAll()} and {@code clear()} are called on the filtered
2036   * multimap or its views, only mappings whose keys satisfy the filter will be removed from the
2037   * underlying multimap.
2038   *
2039   * <p>The returned multimap isn't threadsafe or serializable, even if {@code unfiltered} is.
2040   *
2041   * <p>Many of the filtered multimap's methods, such as {@code size()}, iterate across every
2042   * key/value mapping in the underlying multimap and determine which satisfy the filter. When a
2043   * live view is <i>not</i> needed, it may be faster to copy the filtered multimap and use the
2044   * copy.
2045   *
2046   * <p><b>Warning:</b> {@code keyPredicate} must be <i>consistent with equals</i>, as documented at
2047   * {@link Predicate#apply}. Do not provide a predicate such as {@code
2048   * Predicates.instanceOf(ArrayList.class)}, which is inconsistent with equals.
2049   *
2050   * @since 14.0
2051   */
2052  public static <K extends @Nullable Object, V extends @Nullable Object>
2053      ListMultimap<K, V> filterKeys(
2054          ListMultimap<K, V> unfiltered, final Predicate<? super K> keyPredicate) {
2055    if (unfiltered instanceof FilteredKeyListMultimap) {
2056      FilteredKeyListMultimap<K, V> prev = (FilteredKeyListMultimap<K, V>) unfiltered;
2057      return new FilteredKeyListMultimap<>(
2058          prev.unfiltered(), Predicates.<K>and(prev.keyPredicate, keyPredicate));
2059    } else {
2060      return new FilteredKeyListMultimap<>(unfiltered, keyPredicate);
2061    }
2062  }
2063
2064  /**
2065   * Returns a multimap containing the mappings in {@code unfiltered} whose values satisfy a
2066   * predicate. The returned multimap is a live view of {@code unfiltered}; changes to one affect
2067   * the other.
2068   *
2069   * <p>The resulting multimap's views have iterators that don't support {@code remove()}, but all
2070   * other methods are supported by the multimap and its views. When adding a value that doesn't
2071   * satisfy the predicate, the multimap's {@code put()}, {@code putAll()}, and {@code
2072   * replaceValues()} methods throw an {@link IllegalArgumentException}.
2073   *
2074   * <p>When methods such as {@code removeAll()} and {@code clear()} are called on the filtered
2075   * multimap or its views, only mappings whose value satisfy the filter will be removed from the
2076   * underlying multimap.
2077   *
2078   * <p>The returned multimap isn't threadsafe or serializable, even if {@code unfiltered} is.
2079   *
2080   * <p>Many of the filtered multimap's methods, such as {@code size()}, iterate across every
2081   * key/value mapping in the underlying multimap and determine which satisfy the filter. When a
2082   * live view is <i>not</i> needed, it may be faster to copy the filtered multimap and use the
2083   * copy.
2084   *
2085   * <p><b>Warning:</b> {@code valuePredicate} must be <i>consistent with equals</i>, as documented
2086   * at {@link Predicate#apply}. Do not provide a predicate such as {@code
2087   * Predicates.instanceOf(ArrayList.class)}, which is inconsistent with equals.
2088   *
2089   * @since 11.0
2090   */
2091  public static <K extends @Nullable Object, V extends @Nullable Object>
2092      Multimap<K, V> filterValues(
2093          Multimap<K, V> unfiltered, final Predicate<? super V> valuePredicate) {
2094    return filterEntries(unfiltered, Maps.<V>valuePredicateOnEntries(valuePredicate));
2095  }
2096
2097  /**
2098   * Returns a multimap containing the mappings in {@code unfiltered} whose values satisfy a
2099   * predicate. The returned multimap is a live view of {@code unfiltered}; changes to one affect
2100   * the other.
2101   *
2102   * <p>The resulting multimap's views have iterators that don't support {@code remove()}, but all
2103   * other methods are supported by the multimap and its views. When adding a value that doesn't
2104   * satisfy the predicate, the multimap's {@code put()}, {@code putAll()}, and {@code
2105   * replaceValues()} methods throw an {@link IllegalArgumentException}.
2106   *
2107   * <p>When methods such as {@code removeAll()} and {@code clear()} are called on the filtered
2108   * multimap or its views, only mappings whose value satisfy the filter will be removed from the
2109   * underlying multimap.
2110   *
2111   * <p>The returned multimap isn't threadsafe or serializable, even if {@code unfiltered} is.
2112   *
2113   * <p>Many of the filtered multimap's methods, such as {@code size()}, iterate across every
2114   * key/value mapping in the underlying multimap and determine which satisfy the filter. When a
2115   * live view is <i>not</i> needed, it may be faster to copy the filtered multimap and use the
2116   * copy.
2117   *
2118   * <p><b>Warning:</b> {@code valuePredicate} must be <i>consistent with equals</i>, as documented
2119   * at {@link Predicate#apply}. Do not provide a predicate such as {@code
2120   * Predicates.instanceOf(ArrayList.class)}, which is inconsistent with equals.
2121   *
2122   * @since 14.0
2123   */
2124  public static <K extends @Nullable Object, V extends @Nullable Object>
2125      SetMultimap<K, V> filterValues(
2126          SetMultimap<K, V> unfiltered, final Predicate<? super V> valuePredicate) {
2127    return filterEntries(unfiltered, Maps.<V>valuePredicateOnEntries(valuePredicate));
2128  }
2129
2130  /**
2131   * Returns a multimap containing the mappings in {@code unfiltered} that satisfy a predicate. The
2132   * returned multimap is a live view of {@code unfiltered}; changes to one affect the other.
2133   *
2134   * <p>The resulting multimap's views have iterators that don't support {@code remove()}, but all
2135   * other methods are supported by the multimap and its views. When adding a key/value pair that
2136   * doesn't satisfy the predicate, multimap's {@code put()}, {@code putAll()}, and {@code
2137   * replaceValues()} methods throw an {@link IllegalArgumentException}.
2138   *
2139   * <p>When methods such as {@code removeAll()} and {@code clear()} are called on the filtered
2140   * multimap or its views, only mappings whose keys satisfy the filter will be removed from the
2141   * underlying multimap.
2142   *
2143   * <p>The returned multimap isn't threadsafe or serializable, even if {@code unfiltered} is.
2144   *
2145   * <p>Many of the filtered multimap's methods, such as {@code size()}, iterate across every
2146   * key/value mapping in the underlying multimap and determine which satisfy the filter. When a
2147   * live view is <i>not</i> needed, it may be faster to copy the filtered multimap and use the
2148   * copy.
2149   *
2150   * <p><b>Warning:</b> {@code entryPredicate} must be <i>consistent with equals</i>, as documented
2151   * at {@link Predicate#apply}.
2152   *
2153   * @since 11.0
2154   */
2155  public static <K extends @Nullable Object, V extends @Nullable Object>
2156      Multimap<K, V> filterEntries(
2157          Multimap<K, V> unfiltered, Predicate<? super Entry<K, V>> entryPredicate) {
2158    checkNotNull(entryPredicate);
2159    if (unfiltered instanceof SetMultimap) {
2160      return filterEntries((SetMultimap<K, V>) unfiltered, entryPredicate);
2161    }
2162    return (unfiltered instanceof FilteredMultimap)
2163        ? filterFiltered((FilteredMultimap<K, V>) unfiltered, entryPredicate)
2164        : new FilteredEntryMultimap<K, V>(checkNotNull(unfiltered), entryPredicate);
2165  }
2166
2167  /**
2168   * Returns a multimap containing the mappings in {@code unfiltered} that satisfy a predicate. The
2169   * returned multimap is a live view of {@code unfiltered}; changes to one affect the other.
2170   *
2171   * <p>The resulting multimap's views have iterators that don't support {@code remove()}, but all
2172   * other methods are supported by the multimap and its views. When adding a key/value pair that
2173   * doesn't satisfy the predicate, multimap's {@code put()}, {@code putAll()}, and {@code
2174   * replaceValues()} methods throw an {@link IllegalArgumentException}.
2175   *
2176   * <p>When methods such as {@code removeAll()} and {@code clear()} are called on the filtered
2177   * multimap or its views, only mappings whose keys satisfy the filter will be removed from the
2178   * underlying multimap.
2179   *
2180   * <p>The returned multimap isn't threadsafe or serializable, even if {@code unfiltered} is.
2181   *
2182   * <p>Many of the filtered multimap's methods, such as {@code size()}, iterate across every
2183   * key/value mapping in the underlying multimap and determine which satisfy the filter. When a
2184   * live view is <i>not</i> needed, it may be faster to copy the filtered multimap and use the
2185   * copy.
2186   *
2187   * <p><b>Warning:</b> {@code entryPredicate} must be <i>consistent with equals</i>, as documented
2188   * at {@link Predicate#apply}.
2189   *
2190   * @since 14.0
2191   */
2192  public static <K extends @Nullable Object, V extends @Nullable Object>
2193      SetMultimap<K, V> filterEntries(
2194          SetMultimap<K, V> unfiltered, Predicate<? super Entry<K, V>> entryPredicate) {
2195    checkNotNull(entryPredicate);
2196    return (unfiltered instanceof FilteredSetMultimap)
2197        ? filterFiltered((FilteredSetMultimap<K, V>) unfiltered, entryPredicate)
2198        : new FilteredEntrySetMultimap<K, V>(checkNotNull(unfiltered), entryPredicate);
2199  }
2200
2201  /**
2202   * Support removal operations when filtering a filtered multimap. Since a filtered multimap has
2203   * iterators that don't support remove, passing one to the FilteredEntryMultimap constructor would
2204   * lead to a multimap whose removal operations would fail. This method combines the predicates to
2205   * avoid that problem.
2206   */
2207  private static <K extends @Nullable Object, V extends @Nullable Object>
2208      Multimap<K, V> filterFiltered(
2209          FilteredMultimap<K, V> multimap, Predicate<? super Entry<K, V>> entryPredicate) {
2210    Predicate<Entry<K, V>> predicate =
2211        Predicates.<Entry<K, V>>and(multimap.entryPredicate(), entryPredicate);
2212    return new FilteredEntryMultimap<>(multimap.unfiltered(), predicate);
2213  }
2214
2215  /**
2216   * Support removal operations when filtering a filtered multimap. Since a filtered multimap has
2217   * iterators that don't support remove, passing one to the FilteredEntryMultimap constructor would
2218   * lead to a multimap whose removal operations would fail. This method combines the predicates to
2219   * avoid that problem.
2220   */
2221  private static <K extends @Nullable Object, V extends @Nullable Object>
2222      SetMultimap<K, V> filterFiltered(
2223          FilteredSetMultimap<K, V> multimap, Predicate<? super Entry<K, V>> entryPredicate) {
2224    Predicate<Entry<K, V>> predicate =
2225        Predicates.<Entry<K, V>>and(multimap.entryPredicate(), entryPredicate);
2226    return new FilteredEntrySetMultimap<>(multimap.unfiltered(), predicate);
2227  }
2228
2229  static boolean equalsImpl(Multimap<?, ?> multimap, @CheckForNull Object object) {
2230    if (object == multimap) {
2231      return true;
2232    }
2233    if (object instanceof Multimap) {
2234      Multimap<?, ?> that = (Multimap<?, ?>) object;
2235      return multimap.asMap().equals(that.asMap());
2236    }
2237    return false;
2238  }
2239
2240  // TODO(jlevy): Create methods that filter a SortedSetMultimap.
2241}