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