001/*
002 * Copyright (C) 2008 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.checkEntryNotNull;
021
022import com.google.common.annotations.Beta;
023import com.google.common.annotations.GwtCompatible;
024import com.google.common.annotations.GwtIncompatible;
025import com.google.errorprone.annotations.CanIgnoreReturnValue;
026import com.google.errorprone.annotations.DoNotMock;
027import com.google.j2objc.annotations.Weak;
028import com.google.j2objc.annotations.WeakOuter;
029import java.io.Serializable;
030import java.util.ArrayList;
031import java.util.Arrays;
032import java.util.Collection;
033import java.util.Comparator;
034import java.util.Iterator;
035import java.util.Map;
036import java.util.Map.Entry;
037import java.util.Set;
038import org.checkerframework.checker.nullness.compatqual.MonotonicNonNullDecl;
039import org.checkerframework.checker.nullness.compatqual.NullableDecl;
040
041/**
042 * A {@link Multimap} whose contents will never change, with many other important properties
043 * detailed at {@link ImmutableCollection}.
044 *
045 * <p><b>Warning:</b> avoid <i>direct</i> usage of {@link ImmutableMultimap} as a type (as with
046 * {@link Multimap} itself). Prefer subtypes such as {@link ImmutableSetMultimap} or {@link
047 * ImmutableListMultimap}, which have well-defined {@link #equals} semantics, thus avoiding a common
048 * source of bugs and confusion.
049 *
050 * <p><b>Note:</b> every {@link ImmutableMultimap} offers an {@link #inverse} view, so there is no
051 * need for a distinct {@code ImmutableBiMultimap} type.
052 *
053 * <p><a id="iteration"></a>
054 *
055 * <p><b>Key-grouped iteration.</b> All view collections follow the same iteration order. In all
056 * current implementations, the iteration order always keeps multiple entries with the same key
057 * together. Any creation method that would customarily respect insertion order (such as {@link
058 * #copyOf(Multimap)}) instead preserves key-grouped order by inserting entries for an existing key
059 * immediately after the last entry having that key.
060 *
061 * <p>See the Guava User Guide article on <a href=
062 * "https://github.com/google/guava/wiki/ImmutableCollectionsExplained"> immutable collections</a>.
063 *
064 * @author Jared Levy
065 * @since 2.0
066 */
067@GwtCompatible(emulated = true)
068public abstract class ImmutableMultimap<K, V> extends BaseImmutableMultimap<K, V>
069    implements Serializable {
070
071  /** Returns an empty multimap. */
072  public static <K, V> ImmutableMultimap<K, V> of() {
073    return ImmutableListMultimap.of();
074  }
075
076  /** Returns an immutable multimap containing a single entry. */
077  public static <K, V> ImmutableMultimap<K, V> of(K k1, V v1) {
078    return ImmutableListMultimap.of(k1, v1);
079  }
080
081  /** Returns an immutable multimap containing the given entries, in order. */
082  public static <K, V> ImmutableMultimap<K, V> of(K k1, V v1, K k2, V v2) {
083    return ImmutableListMultimap.of(k1, v1, k2, v2);
084  }
085
086  /**
087   * Returns an immutable multimap containing the given entries, in the "key-grouped" insertion
088   * order described in the <a href="#iteration">class documentation</a>.
089   */
090  public static <K, V> ImmutableMultimap<K, V> of(K k1, V v1, K k2, V v2, K k3, V v3) {
091    return ImmutableListMultimap.of(k1, v1, k2, v2, k3, v3);
092  }
093
094  /**
095   * Returns an immutable multimap containing the given entries, in the "key-grouped" insertion
096   * order described in the <a href="#iteration">class documentation</a>.
097   */
098  public static <K, V> ImmutableMultimap<K, V> of(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4) {
099    return ImmutableListMultimap.of(k1, v1, k2, v2, k3, v3, k4, v4);
100  }
101
102  /**
103   * Returns an immutable multimap containing the given entries, in the "key-grouped" insertion
104   * order described in the <a href="#iteration">class documentation</a>.
105   */
106  public static <K, V> ImmutableMultimap<K, V> of(
107      K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5) {
108    return ImmutableListMultimap.of(k1, v1, k2, v2, k3, v3, k4, v4, k5, v5);
109  }
110
111  // looking for of() with > 5 entries? Use the builder instead.
112
113  /**
114   * Returns a new builder. The generated builder is equivalent to the builder created by the {@link
115   * Builder} constructor.
116   */
117  public static <K, V> Builder<K, V> builder() {
118    return new Builder<>();
119  }
120
121  /**
122   * A builder for creating immutable multimap instances, especially {@code public static final}
123   * multimaps ("constant multimaps"). Example:
124   *
125   * <pre>{@code
126   * static final Multimap<String, Integer> STRING_TO_INTEGER_MULTIMAP =
127   *     new ImmutableMultimap.Builder<String, Integer>()
128   *         .put("one", 1)
129   *         .putAll("several", 1, 2, 3)
130   *         .putAll("many", 1, 2, 3, 4, 5)
131   *         .build();
132   * }</pre>
133   *
134   * <p>Builder instances can be reused; it is safe to call {@link #build} multiple times to build
135   * multiple multimaps in series. Each multimap contains the key-value mappings in the previously
136   * created multimaps.
137   *
138   * @since 2.0
139   */
140  @DoNotMock
141  public static class Builder<K, V> {
142    Map<K, Collection<V>> builderMap;
143    @MonotonicNonNullDecl Comparator<? super K> keyComparator;
144    @MonotonicNonNullDecl Comparator<? super V> valueComparator;
145
146    /**
147     * Creates a new builder. The returned builder is equivalent to the builder generated by {@link
148     * ImmutableMultimap#builder}.
149     */
150    public Builder() {
151      this.builderMap = Platform.preservesInsertionOrderOnPutsMap();
152    }
153
154    Collection<V> newMutableValueCollection() {
155      return new ArrayList<>();
156    }
157
158    /** Adds a key-value mapping to the built multimap. */
159    @CanIgnoreReturnValue
160    public Builder<K, V> put(K key, V value) {
161      checkEntryNotNull(key, value);
162      Collection<V> valueCollection = builderMap.get(key);
163      if (valueCollection == null) {
164        builderMap.put(key, valueCollection = newMutableValueCollection());
165      }
166      valueCollection.add(value);
167      return this;
168    }
169
170    /**
171     * Adds an entry to the built multimap.
172     *
173     * @since 11.0
174     */
175    @CanIgnoreReturnValue
176    public Builder<K, V> put(Entry<? extends K, ? extends V> entry) {
177      return put(entry.getKey(), entry.getValue());
178    }
179
180    /**
181     * Adds entries to the built multimap.
182     *
183     * @since 19.0
184     */
185    @CanIgnoreReturnValue
186    @Beta
187    public Builder<K, V> putAll(Iterable<? extends Entry<? extends K, ? extends V>> entries) {
188      for (Entry<? extends K, ? extends V> entry : entries) {
189        put(entry);
190      }
191      return this;
192    }
193
194    /**
195     * Stores a collection of values with the same key in the built multimap.
196     *
197     * @throws NullPointerException if {@code key}, {@code values}, or any element in {@code values}
198     *     is null. The builder is left in an invalid state.
199     */
200    @CanIgnoreReturnValue
201    public Builder<K, V> putAll(K key, Iterable<? extends V> values) {
202      if (key == null) {
203        throw new NullPointerException("null key in entry: null=" + Iterables.toString(values));
204      }
205      Collection<V> valueCollection = builderMap.get(key);
206      if (valueCollection != null) {
207        for (V value : values) {
208          checkEntryNotNull(key, value);
209          valueCollection.add(value);
210        }
211        return this;
212      }
213      Iterator<? extends V> valuesItr = values.iterator();
214      if (!valuesItr.hasNext()) {
215        return this;
216      }
217      valueCollection = newMutableValueCollection();
218      while (valuesItr.hasNext()) {
219        V value = valuesItr.next();
220        checkEntryNotNull(key, value);
221        valueCollection.add(value);
222      }
223      builderMap.put(key, valueCollection);
224      return this;
225    }
226
227    /**
228     * Stores an array of values with the same key in the built multimap.
229     *
230     * @throws NullPointerException if the key or any value is null. The builder is left in an
231     *     invalid state.
232     */
233    @CanIgnoreReturnValue
234    public Builder<K, V> putAll(K key, V... values) {
235      return putAll(key, Arrays.asList(values));
236    }
237
238    /**
239     * Stores another multimap's entries in the built multimap. The generated multimap's key and
240     * value orderings correspond to the iteration ordering of the {@code multimap.asMap()} view,
241     * with new keys and values following any existing keys and values.
242     *
243     * @throws NullPointerException if any key or value in {@code multimap} is null. The builder is
244     *     left in an invalid state.
245     */
246    @CanIgnoreReturnValue
247    public Builder<K, V> putAll(Multimap<? extends K, ? extends V> multimap) {
248      for (Entry<? extends K, ? extends Collection<? extends V>> entry :
249          multimap.asMap().entrySet()) {
250        putAll(entry.getKey(), entry.getValue());
251      }
252      return this;
253    }
254
255    /**
256     * Specifies the ordering of the generated multimap's keys.
257     *
258     * @since 8.0
259     */
260    @CanIgnoreReturnValue
261    public Builder<K, V> orderKeysBy(Comparator<? super K> keyComparator) {
262      this.keyComparator = checkNotNull(keyComparator);
263      return this;
264    }
265
266    /**
267     * Specifies the ordering of the generated multimap's values for each key.
268     *
269     * @since 8.0
270     */
271    @CanIgnoreReturnValue
272    public Builder<K, V> orderValuesBy(Comparator<? super V> valueComparator) {
273      this.valueComparator = checkNotNull(valueComparator);
274      return this;
275    }
276
277    @CanIgnoreReturnValue
278    Builder<K, V> combine(Builder<K, V> other) {
279      for (Map.Entry<K, Collection<V>> entry : other.builderMap.entrySet()) {
280        putAll(entry.getKey(), entry.getValue());
281      }
282      return this;
283    }
284
285    /** Returns a newly-created immutable multimap. */
286    public ImmutableMultimap<K, V> build() {
287      Collection<Map.Entry<K, Collection<V>>> mapEntries = builderMap.entrySet();
288      if (keyComparator != null) {
289        mapEntries = Ordering.from(keyComparator).<K>onKeys().immutableSortedCopy(mapEntries);
290      }
291      return ImmutableListMultimap.fromMapEntries(mapEntries, valueComparator);
292    }
293  }
294
295  /**
296   * Returns an immutable multimap containing the same mappings as {@code multimap}, in the
297   * "key-grouped" iteration order described in the class documentation.
298   *
299   * <p>Despite the method name, this method attempts to avoid actually copying the data when it is
300   * safe to do so. The exact circumstances under which a copy will or will not be performed are
301   * undocumented and subject to change.
302   *
303   * @throws NullPointerException if any key or value in {@code multimap} is null
304   */
305  public static <K, V> ImmutableMultimap<K, V> copyOf(Multimap<? extends K, ? extends V> multimap) {
306    if (multimap instanceof ImmutableMultimap) {
307      @SuppressWarnings("unchecked") // safe since multimap is not writable
308      ImmutableMultimap<K, V> kvMultimap = (ImmutableMultimap<K, V>) multimap;
309      if (!kvMultimap.isPartialView()) {
310        return kvMultimap;
311      }
312    }
313    return ImmutableListMultimap.copyOf(multimap);
314  }
315
316  /**
317   * Returns an immutable multimap containing the specified entries. The returned multimap iterates
318   * over keys in the order they were first encountered in the input, and the values for each key
319   * are iterated in the order they were encountered.
320   *
321   * @throws NullPointerException if any key, value, or entry is null
322   * @since 19.0
323   */
324  @Beta
325  public static <K, V> ImmutableMultimap<K, V> copyOf(
326      Iterable<? extends Entry<? extends K, ? extends V>> entries) {
327    return ImmutableListMultimap.copyOf(entries);
328  }
329
330  final transient ImmutableMap<K, ? extends ImmutableCollection<V>> map;
331  final transient int size;
332
333  // These constants allow the deserialization code to set final fields. This
334  // holder class makes sure they are not initialized unless an instance is
335  // deserialized.
336  @GwtIncompatible // java serialization is not supported
337  static class FieldSettersHolder {
338    static final Serialization.FieldSetter<ImmutableMultimap> MAP_FIELD_SETTER =
339        Serialization.getFieldSetter(ImmutableMultimap.class, "map");
340    static final Serialization.FieldSetter<ImmutableMultimap> SIZE_FIELD_SETTER =
341        Serialization.getFieldSetter(ImmutableMultimap.class, "size");
342  }
343
344  ImmutableMultimap(ImmutableMap<K, ? extends ImmutableCollection<V>> map, int size) {
345    this.map = map;
346    this.size = size;
347  }
348
349  // mutators (not supported)
350
351  /**
352   * Guaranteed to throw an exception and leave the multimap unmodified.
353   *
354   * @throws UnsupportedOperationException always
355   * @deprecated Unsupported operation.
356   */
357  @CanIgnoreReturnValue
358  @Deprecated
359  @Override
360  public ImmutableCollection<V> removeAll(Object key) {
361    throw new UnsupportedOperationException();
362  }
363
364  /**
365   * Guaranteed to throw an exception and leave the multimap unmodified.
366   *
367   * @throws UnsupportedOperationException always
368   * @deprecated Unsupported operation.
369   */
370  @CanIgnoreReturnValue
371  @Deprecated
372  @Override
373  public ImmutableCollection<V> replaceValues(K key, Iterable<? extends V> values) {
374    throw new UnsupportedOperationException();
375  }
376
377  /**
378   * Guaranteed to throw an exception and leave the multimap unmodified.
379   *
380   * @throws UnsupportedOperationException always
381   * @deprecated Unsupported operation.
382   */
383  @Deprecated
384  @Override
385  public void clear() {
386    throw new UnsupportedOperationException();
387  }
388
389  /**
390   * Returns an immutable collection of the values for the given key. If no mappings in the multimap
391   * have the provided key, an empty immutable collection is returned. The values are in the same
392   * order as the parameters used to build this multimap.
393   */
394  @Override
395  public abstract ImmutableCollection<V> get(K key);
396
397  /**
398   * Returns an immutable multimap which is the inverse of this one. For every key-value mapping in
399   * the original, the result will have a mapping with key and value reversed.
400   *
401   * @since 11.0
402   */
403  public abstract ImmutableMultimap<V, K> inverse();
404
405  /**
406   * Guaranteed to throw an exception and leave the multimap unmodified.
407   *
408   * @throws UnsupportedOperationException always
409   * @deprecated Unsupported operation.
410   */
411  @CanIgnoreReturnValue
412  @Deprecated
413  @Override
414  public boolean put(K key, V value) {
415    throw new UnsupportedOperationException();
416  }
417
418  /**
419   * Guaranteed to throw an exception and leave the multimap unmodified.
420   *
421   * @throws UnsupportedOperationException always
422   * @deprecated Unsupported operation.
423   */
424  @CanIgnoreReturnValue
425  @Deprecated
426  @Override
427  public boolean putAll(K key, Iterable<? extends V> values) {
428    throw new UnsupportedOperationException();
429  }
430
431  /**
432   * Guaranteed to throw an exception and leave the multimap unmodified.
433   *
434   * @throws UnsupportedOperationException always
435   * @deprecated Unsupported operation.
436   */
437  @CanIgnoreReturnValue
438  @Deprecated
439  @Override
440  public boolean putAll(Multimap<? extends K, ? extends V> multimap) {
441    throw new UnsupportedOperationException();
442  }
443
444  /**
445   * Guaranteed to throw an exception and leave the multimap unmodified.
446   *
447   * @throws UnsupportedOperationException always
448   * @deprecated Unsupported operation.
449   */
450  @CanIgnoreReturnValue
451  @Deprecated
452  @Override
453  public boolean remove(Object key, Object value) {
454    throw new UnsupportedOperationException();
455  }
456
457  /**
458   * Returns {@code true} if this immutable multimap's implementation contains references to
459   * user-created objects that aren't accessible via this multimap's methods. This is generally used
460   * to determine whether {@code copyOf} implementations should make an explicit copy to avoid
461   * memory leaks.
462   */
463  boolean isPartialView() {
464    return map.isPartialView();
465  }
466
467  // accessors
468
469  @Override
470  public boolean containsKey(@NullableDecl Object key) {
471    return map.containsKey(key);
472  }
473
474  @Override
475  public boolean containsValue(@NullableDecl Object value) {
476    return value != null && super.containsValue(value);
477  }
478
479  @Override
480  public int size() {
481    return size;
482  }
483
484  // views
485
486  /**
487   * Returns an immutable set of the distinct keys in this multimap, in the same order as they
488   * appear in this multimap.
489   */
490  @Override
491  public ImmutableSet<K> keySet() {
492    return map.keySet();
493  }
494
495  @Override
496  Set<K> createKeySet() {
497    throw new AssertionError("unreachable");
498  }
499
500  /**
501   * Returns an immutable map that associates each key with its corresponding values in the
502   * multimap. Keys and values appear in the same order as in this multimap.
503   */
504  @Override
505  @SuppressWarnings("unchecked") // a widening cast
506  public ImmutableMap<K, Collection<V>> asMap() {
507    return (ImmutableMap) map;
508  }
509
510  @Override
511  Map<K, Collection<V>> createAsMap() {
512    throw new AssertionError("should never be called");
513  }
514
515  /** Returns an immutable collection of all key-value pairs in the multimap. */
516  @Override
517  public ImmutableCollection<Entry<K, V>> entries() {
518    return (ImmutableCollection<Entry<K, V>>) super.entries();
519  }
520
521  @Override
522  ImmutableCollection<Entry<K, V>> createEntries() {
523    return new EntryCollection<>(this);
524  }
525
526  private static class EntryCollection<K, V> extends ImmutableCollection<Entry<K, V>> {
527    @Weak final ImmutableMultimap<K, V> multimap;
528
529    EntryCollection(ImmutableMultimap<K, V> multimap) {
530      this.multimap = multimap;
531    }
532
533    @Override
534    public UnmodifiableIterator<Entry<K, V>> iterator() {
535      return multimap.entryIterator();
536    }
537
538    @Override
539    boolean isPartialView() {
540      return multimap.isPartialView();
541    }
542
543    @Override
544    public int size() {
545      return multimap.size();
546    }
547
548    @Override
549    public boolean contains(Object object) {
550      if (object instanceof Entry) {
551        Entry<?, ?> entry = (Entry<?, ?>) object;
552        return multimap.containsEntry(entry.getKey(), entry.getValue());
553      }
554      return false;
555    }
556
557    private static final long serialVersionUID = 0;
558  }
559
560  @Override
561  UnmodifiableIterator<Entry<K, V>> entryIterator() {
562    return new UnmodifiableIterator<Entry<K, V>>() {
563      final Iterator<? extends Entry<K, ? extends ImmutableCollection<V>>> asMapItr =
564          map.entrySet().iterator();
565      K currentKey = null;
566      Iterator<V> valueItr = Iterators.emptyIterator();
567
568      @Override
569      public boolean hasNext() {
570        return valueItr.hasNext() || asMapItr.hasNext();
571      }
572
573      @Override
574      public Entry<K, V> next() {
575        if (!valueItr.hasNext()) {
576          Entry<K, ? extends ImmutableCollection<V>> entry = asMapItr.next();
577          currentKey = entry.getKey();
578          valueItr = entry.getValue().iterator();
579        }
580        return Maps.immutableEntry(currentKey, valueItr.next());
581      }
582    };
583  }
584
585  /**
586   * Returns an immutable multiset containing all the keys in this multimap, in the same order and
587   * with the same frequencies as they appear in this multimap; to get only a single occurrence of
588   * each key, use {@link #keySet}.
589   */
590  @Override
591  public ImmutableMultiset<K> keys() {
592    return (ImmutableMultiset<K>) super.keys();
593  }
594
595  @Override
596  ImmutableMultiset<K> createKeys() {
597    return new Keys();
598  }
599
600  @SuppressWarnings("serial") // Uses writeReplace, not default serialization
601  @WeakOuter
602  class Keys extends ImmutableMultiset<K> {
603    @Override
604    public boolean contains(@NullableDecl Object object) {
605      return containsKey(object);
606    }
607
608    @Override
609    public int count(@NullableDecl Object element) {
610      Collection<V> values = map.get(element);
611      return (values == null) ? 0 : values.size();
612    }
613
614    @Override
615    public ImmutableSet<K> elementSet() {
616      return keySet();
617    }
618
619    @Override
620    public int size() {
621      return ImmutableMultimap.this.size();
622    }
623
624    @Override
625    Multiset.Entry<K> getEntry(int index) {
626      Map.Entry<K, ? extends Collection<V>> entry = map.entrySet().asList().get(index);
627      return Multisets.immutableEntry(entry.getKey(), entry.getValue().size());
628    }
629
630    @Override
631    boolean isPartialView() {
632      return true;
633    }
634
635    @GwtIncompatible
636    @Override
637    Object writeReplace() {
638      return new KeysSerializedForm(ImmutableMultimap.this);
639    }
640  }
641
642  @GwtIncompatible
643  private static final class KeysSerializedForm implements Serializable {
644    final ImmutableMultimap<?, ?> multimap;
645
646    KeysSerializedForm(ImmutableMultimap<?, ?> multimap) {
647      this.multimap = multimap;
648    }
649
650    Object readResolve() {
651      return multimap.keys();
652    }
653  }
654
655  /**
656   * Returns an immutable collection of the values in this multimap. Its iterator traverses the
657   * values for the first key, the values for the second key, and so on.
658   */
659  @Override
660  public ImmutableCollection<V> values() {
661    return (ImmutableCollection<V>) super.values();
662  }
663
664  @Override
665  ImmutableCollection<V> createValues() {
666    return new Values<>(this);
667  }
668
669  @Override
670  UnmodifiableIterator<V> valueIterator() {
671    return new UnmodifiableIterator<V>() {
672      Iterator<? extends ImmutableCollection<V>> valueCollectionItr = map.values().iterator();
673      Iterator<V> valueItr = Iterators.emptyIterator();
674
675      @Override
676      public boolean hasNext() {
677        return valueItr.hasNext() || valueCollectionItr.hasNext();
678      }
679
680      @Override
681      public V next() {
682        if (!valueItr.hasNext()) {
683          valueItr = valueCollectionItr.next().iterator();
684        }
685        return valueItr.next();
686      }
687    };
688  }
689
690  private static final class Values<K, V> extends ImmutableCollection<V> {
691    @Weak private final transient ImmutableMultimap<K, V> multimap;
692
693    Values(ImmutableMultimap<K, V> multimap) {
694      this.multimap = multimap;
695    }
696
697    @Override
698    public boolean contains(@NullableDecl Object object) {
699      return multimap.containsValue(object);
700    }
701
702    @Override
703    public UnmodifiableIterator<V> iterator() {
704      return multimap.valueIterator();
705    }
706
707    @GwtIncompatible // not present in emulated superclass
708    @Override
709    int copyIntoArray(Object[] dst, int offset) {
710      for (ImmutableCollection<V> valueCollection : multimap.map.values()) {
711        offset = valueCollection.copyIntoArray(dst, offset);
712      }
713      return offset;
714    }
715
716    @Override
717    public int size() {
718      return multimap.size();
719    }
720
721    @Override
722    boolean isPartialView() {
723      return true;
724    }
725
726    private static final long serialVersionUID = 0;
727  }
728
729  private static final long serialVersionUID = 0;
730}