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