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