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