001/*
002 * Copyright (C) 2009 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 java.lang.Math.max;
022import static java.util.Arrays.asList;
023import static java.util.Objects.requireNonNull;
024
025import com.google.common.annotations.GwtCompatible;
026import com.google.common.annotations.GwtIncompatible;
027import com.google.common.annotations.J2ktIncompatible;
028import com.google.common.base.MoreObjects;
029import com.google.errorprone.annotations.CanIgnoreReturnValue;
030import com.google.errorprone.annotations.DoNotCall;
031import com.google.errorprone.annotations.concurrent.LazyInit;
032import com.google.j2objc.annotations.RetainedWith;
033import com.google.j2objc.annotations.Weak;
034import java.io.IOException;
035import java.io.InvalidObjectException;
036import java.io.ObjectInputStream;
037import java.io.ObjectOutputStream;
038import java.util.Collection;
039import java.util.Comparator;
040import java.util.Map;
041import java.util.Map.Entry;
042import java.util.Set;
043import java.util.function.Function;
044import java.util.stream.Collector;
045import java.util.stream.Stream;
046import javax.annotation.CheckForNull;
047import org.checkerframework.checker.nullness.qual.Nullable;
048
049/**
050 * A {@link SetMultimap} whose contents will never change, with many other important properties
051 * detailed at {@link ImmutableCollection}.
052 *
053 * <p><b>Warning:</b> As in all {@link SetMultimap}s, do not modify either a key <i>or a value</i>
054 * of a {@code ImmutableSetMultimap} in a way that affects its {@link Object#equals} behavior.
055 * Undefined behavior and bugs will result.
056 *
057 * <p>See the Guava User Guide article on <a href=
058 * "https://github.com/google/guava/wiki/ImmutableCollectionsExplained">immutable collections</a>.
059 *
060 * @author Mike Ward
061 * @since 2.0
062 */
063@GwtCompatible(serializable = true, emulated = true)
064public class ImmutableSetMultimap<K, V> extends ImmutableMultimap<K, V>
065    implements SetMultimap<K, V> {
066  /**
067   * Returns a {@link Collector} that accumulates elements into an {@code ImmutableSetMultimap}
068   * whose keys and values are the result of applying the provided mapping functions to the input
069   * elements.
070   *
071   * <p>For streams with defined encounter order (as defined in the Ordering section of the {@link
072   * java.util.stream} Javadoc), that order is preserved, but entries are <a
073   * href="ImmutableMultimap.html#iteration">grouped by key</a>.
074   *
075   * <p>Example:
076   *
077   * <pre>{@code
078   * static final Multimap<Character, String> FIRST_LETTER_MULTIMAP =
079   *     Stream.of("banana", "apple", "carrot", "asparagus", "cherry")
080   *         .collect(toImmutableSetMultimap(str -> str.charAt(0), str -> str.substring(1)));
081   *
082   * // is equivalent to
083   *
084   * static final Multimap<Character, String> FIRST_LETTER_MULTIMAP =
085   *     new ImmutableSetMultimap.Builder<Character, String>()
086   *         .put('b', "anana")
087   *         .putAll('a', "pple", "sparagus")
088   *         .putAll('c', "arrot", "herry")
089   *         .build();
090   * }</pre>
091   *
092   * @since 33.2.0 (available since 21.0 in guava-jre)
093   */
094  @SuppressWarnings("Java7ApiChecker")
095  @IgnoreJRERequirement // Users will use this only if they're already using streams.
096  public static <T extends @Nullable Object, K, V>
097      Collector<T, ?, ImmutableSetMultimap<K, V>> toImmutableSetMultimap(
098          Function<? super T, ? extends K> keyFunction,
099          Function<? super T, ? extends V> valueFunction) {
100    return CollectCollectors.toImmutableSetMultimap(keyFunction, valueFunction);
101  }
102
103  /**
104   * Returns a {@code Collector} accumulating entries into an {@code ImmutableSetMultimap}. Each
105   * input element is mapped to a key and a stream of values, each of which are put into the
106   * resulting {@code Multimap}, in the encounter order of the stream and the encounter order of the
107   * streams of values.
108   *
109   * <p>Example:
110   *
111   * <pre>{@code
112   * static final ImmutableSetMultimap<Character, Character> FIRST_LETTER_MULTIMAP =
113   *     Stream.of("banana", "apple", "carrot", "asparagus", "cherry")
114   *         .collect(
115   *             flatteningToImmutableSetMultimap(
116   *                  str -> str.charAt(0),
117   *                  str -> str.substring(1).chars().mapToObj(c -> (char) c));
118   *
119   * // is equivalent to
120   *
121   * static final ImmutableSetMultimap<Character, Character> FIRST_LETTER_MULTIMAP =
122   *     ImmutableSetMultimap.<Character, Character>builder()
123   *         .putAll('b', Arrays.asList('a', 'n', 'a', 'n', 'a'))
124   *         .putAll('a', Arrays.asList('p', 'p', 'l', 'e'))
125   *         .putAll('c', Arrays.asList('a', 'r', 'r', 'o', 't'))
126   *         .putAll('a', Arrays.asList('s', 'p', 'a', 'r', 'a', 'g', 'u', 's'))
127   *         .putAll('c', Arrays.asList('h', 'e', 'r', 'r', 'y'))
128   *         .build();
129   *
130   * // after deduplication, the resulting multimap is equivalent to
131   *
132   * static final ImmutableSetMultimap<Character, Character> FIRST_LETTER_MULTIMAP =
133   *     ImmutableSetMultimap.<Character, Character>builder()
134   *         .putAll('b', Arrays.asList('a', 'n'))
135   *         .putAll('a', Arrays.asList('p', 'l', 'e', 's', 'a', 'r', 'g', 'u'))
136   *         .putAll('c', Arrays.asList('a', 'r', 'o', 't', 'h', 'e', 'y'))
137   *         .build();
138   * }
139   * }</pre>
140   *
141   * @since 33.2.0 (available since 21.0 in guava-jre)
142   */
143  @SuppressWarnings("Java7ApiChecker")
144  @IgnoreJRERequirement // Users will use this only if they're already using streams.
145  public static <T extends @Nullable Object, K, V>
146      Collector<T, ?, ImmutableSetMultimap<K, V>> flatteningToImmutableSetMultimap(
147          Function<? super T, ? extends K> keyFunction,
148          Function<? super T, ? extends Stream<? extends V>> valuesFunction) {
149    return CollectCollectors.flatteningToImmutableSetMultimap(keyFunction, valuesFunction);
150  }
151
152  /**
153   * Returns the empty multimap.
154   *
155   * <p><b>Performance note:</b> the instance returned is a singleton.
156   */
157  // Casting is safe because the multimap will never hold any elements.
158  @SuppressWarnings("unchecked")
159  public static <K, V> ImmutableSetMultimap<K, V> of() {
160    return (ImmutableSetMultimap<K, V>) EmptyImmutableSetMultimap.INSTANCE;
161  }
162
163  /** Returns an immutable multimap containing a single entry. */
164  public static <K, V> ImmutableSetMultimap<K, V> of(K k1, V v1) {
165    ImmutableSetMultimap.Builder<K, V> builder = ImmutableSetMultimap.builder();
166    builder.put(k1, v1);
167    return builder.build();
168  }
169
170  /**
171   * Returns an immutable multimap containing the given entries, in order. Repeated occurrences of
172   * an entry (according to {@link Object#equals}) after the first are ignored.
173   */
174  public static <K, V> ImmutableSetMultimap<K, V> of(K k1, V v1, K k2, V v2) {
175    ImmutableSetMultimap.Builder<K, V> builder = ImmutableSetMultimap.builder();
176    builder.put(k1, v1);
177    builder.put(k2, v2);
178    return builder.build();
179  }
180
181  /**
182   * Returns an immutable multimap containing the given entries, in order. Repeated occurrences of
183   * an entry (according to {@link Object#equals}) after the first are ignored.
184   */
185  public static <K, V> ImmutableSetMultimap<K, V> of(K k1, V v1, K k2, V v2, K k3, V v3) {
186    ImmutableSetMultimap.Builder<K, V> builder = ImmutableSetMultimap.builder();
187    builder.put(k1, v1);
188    builder.put(k2, v2);
189    builder.put(k3, v3);
190    return builder.build();
191  }
192
193  /**
194   * Returns an immutable multimap containing the given entries, in order. Repeated occurrences of
195   * an entry (according to {@link Object#equals}) after the first are ignored.
196   */
197  public static <K, V> ImmutableSetMultimap<K, V> of(
198      K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4) {
199    ImmutableSetMultimap.Builder<K, V> builder = ImmutableSetMultimap.builder();
200    builder.put(k1, v1);
201    builder.put(k2, v2);
202    builder.put(k3, v3);
203    builder.put(k4, v4);
204    return builder.build();
205  }
206
207  /**
208   * Returns an immutable multimap containing the given entries, in order. Repeated occurrences of
209   * an entry (according to {@link Object#equals}) after the first are ignored.
210   */
211  public static <K, V> ImmutableSetMultimap<K, V> of(
212      K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5) {
213    ImmutableSetMultimap.Builder<K, V> builder = ImmutableSetMultimap.builder();
214    builder.put(k1, v1);
215    builder.put(k2, v2);
216    builder.put(k3, v3);
217    builder.put(k4, v4);
218    builder.put(k5, v5);
219    return builder.build();
220  }
221
222  // looking for of() with > 5 entries? Use the builder instead.
223
224  /** Returns a new {@link Builder}. */
225  public static <K, V> Builder<K, V> builder() {
226    return new Builder<>();
227  }
228
229  /**
230   * Returns a new builder with a hint for how many distinct keys are expected to be added. The
231   * generated builder is equivalent to that returned by {@link #builder}, but may perform better if
232   * {@code expectedKeys} is a good estimate.
233   *
234   * @throws IllegalArgumentException if {@code expectedKeys} is negative
235   * @since 33.3.0
236   */
237  public static <K, V> Builder<K, V> builderWithExpectedKeys(int expectedKeys) {
238    checkNonnegative(expectedKeys, "expectedKeys");
239    return new Builder<>(expectedKeys);
240  }
241
242  /**
243   * A builder for creating immutable {@code SetMultimap} instances, especially {@code public static
244   * final} multimaps ("constant multimaps"). Example:
245   *
246   * <pre>{@code
247   * static final Multimap<String, Integer> STRING_TO_INTEGER_MULTIMAP =
248   *     new ImmutableSetMultimap.Builder<String, Integer>()
249   *         .put("one", 1)
250   *         .putAll("several", 1, 2, 3)
251   *         .putAll("many", 1, 2, 3, 4, 5)
252   *         .build();
253   * }</pre>
254   *
255   * <p>Builder instances can be reused; it is safe to call {@link #build} multiple times to build
256   * multiple multimaps in series. Each multimap contains the key-value mappings in the previously
257   * created multimaps.
258   *
259   * @since 2.0
260   */
261  public static final class Builder<K, V> extends ImmutableMultimap.Builder<K, V> {
262    /**
263     * Creates a new builder. The returned builder is equivalent to the builder generated by {@link
264     * ImmutableSetMultimap#builder}.
265     */
266    public Builder() {
267      super();
268    }
269
270    Builder(int expectedKeys) {
271      super(expectedKeys);
272    }
273
274    @Override
275    ImmutableCollection.Builder<V> newValueCollectionBuilderWithExpectedSize(int expectedSize) {
276      return (valueComparator == null)
277          ? ImmutableSet.builderWithExpectedSize(expectedSize)
278          : new ImmutableSortedSet.Builder<V>(valueComparator, expectedSize);
279    }
280
281    @Override
282    int expectedValueCollectionSize(int defaultExpectedValues, Iterable<?> values) {
283      // Only trust the size of `values` if it is a Set and therefore probably already deduplicated.
284      if (values instanceof Set<?>) {
285        Set<?> collection = (Set<?>) values;
286        return max(defaultExpectedValues, collection.size());
287      } else {
288        return defaultExpectedValues;
289      }
290    }
291
292    /**
293     * {@inheritDoc}
294     *
295     * <p>Note that {@code expectedValuesPerKey} is taken to mean the expected number of
296     * <i>distinct</i> values per key.
297     *
298     * @since 33.3.0
299     */
300    @CanIgnoreReturnValue
301    @Override
302    public Builder<K, V> expectedValuesPerKey(int expectedValuesPerKey) {
303      super.expectedValuesPerKey(expectedValuesPerKey);
304      return this;
305    }
306
307    /** Adds a key-value mapping to the built multimap if it is not already present. */
308    @CanIgnoreReturnValue
309    @Override
310    public Builder<K, V> put(K key, V value) {
311      super.put(key, value);
312      return this;
313    }
314
315    /**
316     * Adds an entry to the built multimap if it is not already present.
317     *
318     * @since 11.0
319     */
320    @CanIgnoreReturnValue
321    @Override
322    public Builder<K, V> put(Entry<? extends K, ? extends V> entry) {
323      super.put(entry);
324      return this;
325    }
326
327    /**
328     * {@inheritDoc}
329     *
330     * @since 19.0
331     */
332    @CanIgnoreReturnValue
333    @Override
334    public Builder<K, V> putAll(Iterable<? extends Entry<? extends K, ? extends V>> entries) {
335      super.putAll(entries);
336      return this;
337    }
338
339    @CanIgnoreReturnValue
340    @Override
341    public Builder<K, V> putAll(K key, Iterable<? extends V> values) {
342      super.putAll(key, values);
343      return this;
344    }
345
346    @CanIgnoreReturnValue
347    @Override
348    public Builder<K, V> putAll(K key, V... values) {
349      return putAll(key, asList(values));
350    }
351
352    @CanIgnoreReturnValue
353    @Override
354    public Builder<K, V> putAll(Multimap<? extends K, ? extends V> multimap) {
355      for (Entry<? extends K, ? extends Collection<? extends V>> entry :
356          multimap.asMap().entrySet()) {
357        putAll(entry.getKey(), entry.getValue());
358      }
359      return this;
360    }
361
362    @CanIgnoreReturnValue
363    @Override
364    Builder<K, V> combine(ImmutableMultimap.Builder<K, V> other) {
365      super.combine(other);
366      return this;
367    }
368
369    /**
370     * {@inheritDoc}
371     *
372     * @since 8.0
373     */
374    @CanIgnoreReturnValue
375    @Override
376    public Builder<K, V> orderKeysBy(Comparator<? super K> keyComparator) {
377      super.orderKeysBy(keyComparator);
378      return this;
379    }
380
381    /**
382     * Specifies the ordering of the generated multimap's values for each key.
383     *
384     * <p>If this method is called, the sets returned by the {@code get()} method of the generated
385     * multimap and its {@link Multimap#asMap()} view are {@link ImmutableSortedSet} instances.
386     * However, serialization does not preserve that property, though it does maintain the key and
387     * value ordering.
388     *
389     * @since 8.0
390     */
391    // TODO: Make serialization behavior consistent.
392    @CanIgnoreReturnValue
393    @Override
394    public Builder<K, V> orderValuesBy(Comparator<? super V> valueComparator) {
395      super.orderValuesBy(valueComparator);
396      return this;
397    }
398
399    /** Returns a newly-created immutable set multimap. */
400    @Override
401    public ImmutableSetMultimap<K, V> build() {
402      if (builderMap == null) {
403        return ImmutableSetMultimap.of();
404      }
405      Collection<Map.Entry<K, ImmutableCollection.Builder<V>>> mapEntries = builderMap.entrySet();
406      if (keyComparator != null) {
407        mapEntries = Ordering.from(keyComparator).<K>onKeys().immutableSortedCopy(mapEntries);
408      }
409      return fromMapBuilderEntries(mapEntries, valueComparator);
410    }
411  }
412
413  /**
414   * Returns an immutable set multimap containing the same mappings as {@code multimap}. The
415   * generated multimap's key and value orderings correspond to the iteration ordering of the {@code
416   * multimap.asMap()} view. Repeated occurrences of an entry in the multimap after the first are
417   * ignored.
418   *
419   * <p>Despite the method name, this method attempts to avoid actually copying the data when it is
420   * safe to do so. The exact circumstances under which a copy will or will not be performed are
421   * undocumented and subject to change.
422   *
423   * @throws NullPointerException if any key or value in {@code multimap} is null
424   */
425  public static <K, V> ImmutableSetMultimap<K, V> copyOf(
426      Multimap<? extends K, ? extends V> multimap) {
427    return copyOf(multimap, null);
428  }
429
430  private static <K, V> ImmutableSetMultimap<K, V> copyOf(
431      Multimap<? extends K, ? extends V> multimap,
432      @CheckForNull Comparator<? super V> valueComparator) {
433    checkNotNull(multimap); // eager for GWT
434    if (multimap.isEmpty() && valueComparator == null) {
435      return of();
436    }
437
438    if (multimap instanceof ImmutableSetMultimap) {
439      @SuppressWarnings("unchecked") // safe since multimap is not writable
440      ImmutableSetMultimap<K, V> kvMultimap = (ImmutableSetMultimap<K, V>) multimap;
441      if (!kvMultimap.isPartialView()) {
442        return kvMultimap;
443      }
444    }
445
446    return fromMapEntries(multimap.asMap().entrySet(), valueComparator);
447  }
448
449  /**
450   * Returns an immutable multimap containing the specified entries. The returned multimap iterates
451   * over keys in the order they were first encountered in the input, and the values for each key
452   * are iterated in the order they were encountered. If two values for the same key are {@linkplain
453   * Object#equals equal}, the first value encountered is used.
454   *
455   * @throws NullPointerException if any key, value, or entry is null
456   * @since 19.0
457   */
458  public static <K, V> ImmutableSetMultimap<K, V> copyOf(
459      Iterable<? extends Entry<? extends K, ? extends V>> entries) {
460    return new Builder<K, V>().putAll(entries).build();
461  }
462
463  /** Creates an ImmutableSetMultimap from an asMap.entrySet. */
464  static <K, V> ImmutableSetMultimap<K, V> fromMapEntries(
465      Collection<? extends Map.Entry<? extends K, ? extends Collection<? extends V>>> mapEntries,
466      @CheckForNull Comparator<? super V> valueComparator) {
467    if (mapEntries.isEmpty()) {
468      return of();
469    }
470    ImmutableMap.Builder<K, ImmutableSet<V>> builder =
471        new ImmutableMap.Builder<>(mapEntries.size());
472    int size = 0;
473
474    for (Entry<? extends K, ? extends Collection<? extends V>> entry : mapEntries) {
475      K key = entry.getKey();
476      Collection<? extends V> values = entry.getValue();
477      ImmutableSet<V> set = valueSet(valueComparator, values);
478      if (!set.isEmpty()) {
479        builder.put(key, set);
480        size += set.size();
481      }
482    }
483
484    return new ImmutableSetMultimap<>(builder.buildOrThrow(), size, valueComparator);
485  }
486
487  /** Creates an ImmutableSetMultimap from a map to builders. */
488  static <K, V> ImmutableSetMultimap<K, V> fromMapBuilderEntries(
489      Collection<? extends Map.Entry<K, ImmutableCollection.Builder<V>>> mapEntries,
490      @CheckForNull Comparator<? super V> valueComparator) {
491    if (mapEntries.isEmpty()) {
492      return of();
493    }
494    ImmutableMap.Builder<K, ImmutableSet<V>> builder =
495        new ImmutableMap.Builder<>(mapEntries.size());
496    int size = 0;
497
498    for (Entry<K, ImmutableCollection.Builder<V>> entry : mapEntries) {
499      K key = entry.getKey();
500      ImmutableSet.Builder<? extends V> values = (ImmutableSet.Builder<V>) entry.getValue();
501      // If orderValuesBy got called at the very end, we may need to do the ImmutableSet to
502      // ImmutableSortedSet copy for each of these.
503      ImmutableSet<V> set = valueSet(valueComparator, values.build());
504      if (!set.isEmpty()) {
505        builder.put(key, set);
506        size += set.size();
507      }
508    }
509
510    return new ImmutableSetMultimap<>(builder.buildOrThrow(), size, valueComparator);
511  }
512
513  /**
514   * Returned by get() when a missing key is provided. Also holds the comparator, if any, used for
515   * values.
516   */
517  private final transient ImmutableSet<V> emptySet;
518
519  ImmutableSetMultimap(
520      ImmutableMap<K, ImmutableSet<V>> map,
521      int size,
522      @CheckForNull Comparator<? super V> valueComparator) {
523    super(map, size);
524    this.emptySet = emptySet(valueComparator);
525  }
526
527  // views
528
529  /**
530   * Returns an immutable set of the values for the given key. If no mappings in the multimap have
531   * the provided key, an empty immutable set is returned. The values are in the same order as the
532   * parameters used to build this multimap.
533   */
534  @Override
535  public ImmutableSet<V> get(K key) {
536    // This cast is safe as its type is known in constructor.
537    ImmutableSet<V> set = (ImmutableSet<V>) map.get(key);
538    return MoreObjects.firstNonNull(set, emptySet);
539  }
540
541  @LazyInit @RetainedWith @CheckForNull private transient ImmutableSetMultimap<V, K> inverse;
542
543  /**
544   * {@inheritDoc}
545   *
546   * <p>Because an inverse of a set multimap cannot contain multiple pairs with the same key and
547   * value, this method returns an {@code ImmutableSetMultimap} rather than the {@code
548   * ImmutableMultimap} specified in the {@code ImmutableMultimap} class.
549   */
550  @Override
551  public ImmutableSetMultimap<V, K> inverse() {
552    ImmutableSetMultimap<V, K> result = inverse;
553    return (result == null) ? (inverse = invert()) : result;
554  }
555
556  private ImmutableSetMultimap<V, K> invert() {
557    Builder<V, K> builder = builder();
558    for (Entry<K, V> entry : entries()) {
559      builder.put(entry.getValue(), entry.getKey());
560    }
561    ImmutableSetMultimap<V, K> invertedMultimap = builder.build();
562    invertedMultimap.inverse = this;
563    return invertedMultimap;
564  }
565
566  /**
567   * Guaranteed to throw an exception and leave the multimap unmodified.
568   *
569   * @throws UnsupportedOperationException always
570   * @deprecated Unsupported operation.
571   */
572  @CanIgnoreReturnValue
573  @Deprecated
574  @Override
575  @DoNotCall("Always throws UnsupportedOperationException")
576  public final ImmutableSet<V> removeAll(@CheckForNull Object key) {
577    throw new UnsupportedOperationException();
578  }
579
580  /**
581   * Guaranteed to throw an exception and leave the multimap unmodified.
582   *
583   * @throws UnsupportedOperationException always
584   * @deprecated Unsupported operation.
585   */
586  @CanIgnoreReturnValue
587  @Deprecated
588  @Override
589  @DoNotCall("Always throws UnsupportedOperationException")
590  public final ImmutableSet<V> replaceValues(K key, Iterable<? extends V> values) {
591    throw new UnsupportedOperationException();
592  }
593
594  @LazyInit @RetainedWith @CheckForNull private transient ImmutableSet<Entry<K, V>> entries;
595
596  /**
597   * Returns an immutable collection of all key-value pairs in the multimap. Its iterator traverses
598   * the values for the first key, the values for the second key, and so on.
599   */
600  @Override
601  public ImmutableSet<Entry<K, V>> entries() {
602    ImmutableSet<Entry<K, V>> result = entries;
603    return result == null ? (entries = new EntrySet<>(this)) : result;
604  }
605
606  private static final class EntrySet<K, V> extends ImmutableSet<Entry<K, V>> {
607    @Weak private final transient ImmutableSetMultimap<K, V> multimap;
608
609    EntrySet(ImmutableSetMultimap<K, V> multimap) {
610      this.multimap = multimap;
611    }
612
613    @Override
614    public boolean contains(@CheckForNull Object object) {
615      if (object instanceof Entry) {
616        Entry<?, ?> entry = (Entry<?, ?>) object;
617        return multimap.containsEntry(entry.getKey(), entry.getValue());
618      }
619      return false;
620    }
621
622    @Override
623    public int size() {
624      return multimap.size();
625    }
626
627    @Override
628    public UnmodifiableIterator<Entry<K, V>> iterator() {
629      return multimap.entryIterator();
630    }
631
632    @Override
633    boolean isPartialView() {
634      return false;
635    }
636
637    // redeclare to help optimizers with b/310253115
638    @SuppressWarnings("RedundantOverride")
639    @Override
640    @J2ktIncompatible // serialization
641    @GwtIncompatible // serialization
642    Object writeReplace() {
643      return super.writeReplace();
644    }
645  }
646
647  private static <V> ImmutableSet<V> valueSet(
648      @CheckForNull Comparator<? super V> valueComparator, Collection<? extends V> values) {
649    return (valueComparator == null)
650        ? ImmutableSet.copyOf(values)
651        : ImmutableSortedSet.copyOf(valueComparator, values);
652  }
653
654  private static <V> ImmutableSet<V> emptySet(@CheckForNull Comparator<? super V> valueComparator) {
655    return (valueComparator == null)
656        ? ImmutableSet.<V>of()
657        : ImmutableSortedSet.<V>emptySet(valueComparator);
658  }
659
660  private static <V> ImmutableSet.Builder<V> valuesBuilder(
661      @CheckForNull Comparator<? super V> valueComparator) {
662    return (valueComparator == null)
663        ? new ImmutableSet.Builder<V>()
664        : new ImmutableSortedSet.Builder<V>(valueComparator);
665  }
666
667  /**
668   * @serialData number of distinct keys, and then for each distinct key: the key, the number of
669   *     values for that key, and the key's values
670   */
671  @GwtIncompatible // java.io.ObjectOutputStream
672  @J2ktIncompatible
673  private void writeObject(ObjectOutputStream stream) throws IOException {
674    stream.defaultWriteObject();
675    stream.writeObject(valueComparator());
676    Serialization.writeMultimap(this, stream);
677  }
678
679  @CheckForNull
680  Comparator<? super V> valueComparator() {
681    return emptySet instanceof ImmutableSortedSet
682        ? ((ImmutableSortedSet<V>) emptySet).comparator()
683        : null;
684  }
685
686  @GwtIncompatible // java serialization
687  @J2ktIncompatible
688  private static final class SetFieldSettersHolder {
689    static final Serialization.FieldSetter<? super ImmutableSetMultimap<?, ?>>
690        EMPTY_SET_FIELD_SETTER =
691            Serialization.getFieldSetter(ImmutableSetMultimap.class, "emptySet");
692  }
693
694  @GwtIncompatible // java.io.ObjectInputStream
695  @J2ktIncompatible
696  // Serialization type safety is at the caller's mercy.
697  @SuppressWarnings("unchecked")
698  private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
699    stream.defaultReadObject();
700    Comparator<Object> valueComparator = (Comparator<Object>) stream.readObject();
701    int keyCount = stream.readInt();
702    if (keyCount < 0) {
703      throw new InvalidObjectException("Invalid key count " + keyCount);
704    }
705    ImmutableMap.Builder<Object, ImmutableSet<Object>> builder = ImmutableMap.builder();
706    int tmpSize = 0;
707
708    for (int i = 0; i < keyCount; i++) {
709      Object key = requireNonNull(stream.readObject());
710      int valueCount = stream.readInt();
711      if (valueCount <= 0) {
712        throw new InvalidObjectException("Invalid value count " + valueCount);
713      }
714
715      ImmutableSet.Builder<Object> valuesBuilder = valuesBuilder(valueComparator);
716      for (int j = 0; j < valueCount; j++) {
717        valuesBuilder.add(requireNonNull(stream.readObject()));
718      }
719      ImmutableSet<Object> valueSet = valuesBuilder.build();
720      if (valueSet.size() != valueCount) {
721        throw new InvalidObjectException("Duplicate key-value pairs exist for key " + key);
722      }
723      builder.put(key, valueSet);
724      tmpSize += valueCount;
725    }
726
727    ImmutableMap<Object, ImmutableSet<Object>> tmpMap;
728    try {
729      tmpMap = builder.buildOrThrow();
730    } catch (IllegalArgumentException e) {
731      throw (InvalidObjectException) new InvalidObjectException(e.getMessage()).initCause(e);
732    }
733
734    FieldSettersHolder.MAP_FIELD_SETTER.set(this, tmpMap);
735    FieldSettersHolder.SIZE_FIELD_SETTER.set(this, tmpSize);
736    SetFieldSettersHolder.EMPTY_SET_FIELD_SETTER.set(this, emptySet(valueComparator));
737  }
738
739  @GwtIncompatible // not needed in emulated source.
740  @J2ktIncompatible
741  private static final long serialVersionUID = 0;
742}