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