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