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