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 java.util.Objects.requireNonNull;
021
022import com.google.common.annotations.Beta;
023import com.google.common.annotations.GwtCompatible;
024import com.google.common.annotations.GwtIncompatible;
025import com.google.common.annotations.J2ktIncompatible;
026import com.google.common.base.MoreObjects;
027import com.google.errorprone.annotations.CanIgnoreReturnValue;
028import com.google.errorprone.annotations.DoNotCall;
029import com.google.errorprone.annotations.concurrent.LazyInit;
030import com.google.j2objc.annotations.RetainedWith;
031import com.google.j2objc.annotations.Weak;
032import java.io.IOException;
033import java.io.InvalidObjectException;
034import java.io.ObjectInputStream;
035import java.io.ObjectOutputStream;
036import java.util.Arrays;
037import java.util.Collection;
038import java.util.Comparator;
039import java.util.Map;
040import java.util.Map.Entry;
041import java.util.function.Function;
042import java.util.stream.Collector;
043import java.util.stream.Stream;
044import javax.annotation.CheckForNull;
045import org.checkerframework.checker.nullness.qual.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(serializable = true, emulated = true)
062@ElementTypesAreNonnullByDefault
063public class ImmutableSetMultimap<K, V> extends ImmutableMultimap<K, V>
064    implements SetMultimap<K, V> {
065  /**
066   * Returns a {@link Collector} that accumulates elements into an {@code ImmutableSetMultimap}
067   * whose keys and values are the result of applying the provided mapping functions to the input
068   * elements.
069   *
070   * <p>For streams with defined encounter order (as defined in the Ordering section of the {@link
071   * java.util.stream} Javadoc), that order is preserved, but entries are <a
072   * href="ImmutableMultimap.html#iteration">grouped by key</a>.
073   *
074   * <p>Example:
075   *
076   * <pre>{@code
077   * static final Multimap<Character, String> FIRST_LETTER_MULTIMAP =
078   *     Stream.of("banana", "apple", "carrot", "asparagus", "cherry")
079   *         .collect(toImmutableSetMultimap(str -> str.charAt(0), str -> str.substring(1)));
080   *
081   * // is equivalent to
082   *
083   * static final Multimap<Character, String> FIRST_LETTER_MULTIMAP =
084   *     new ImmutableSetMultimap.Builder<Character, String>()
085   *         .put('b', "anana")
086   *         .putAll('a', "pple", "sparagus")
087   *         .putAll('c', "arrot", "herry")
088   *         .build();
089   * }</pre>
090   *
091   * @since 33.2.0 (available since 21.0 in guava-jre)
092   */
093  @SuppressWarnings({"AndroidJdkLibsChecker", "Java7ApiChecker"})
094  @IgnoreJRERequirement // Users will use this only if they're already using streams.
095  @Beta // TODO: b/288085449 - Remove.
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({"AndroidJdkLibsChecker", "Java7ApiChecker"})
144  @IgnoreJRERequirement // Users will use this only if they're already using streams.
145  @Beta // TODO: b/288085449 - Remove.
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   * A builder for creating immutable {@code SetMultimap} instances, especially {@code public static
232   * final} multimaps ("constant multimaps"). Example:
233   *
234   * <pre>{@code
235   * static final Multimap<String, Integer> STRING_TO_INTEGER_MULTIMAP =
236   *     new ImmutableSetMultimap.Builder<String, Integer>()
237   *         .put("one", 1)
238   *         .putAll("several", 1, 2, 3)
239   *         .putAll("many", 1, 2, 3, 4, 5)
240   *         .build();
241   * }</pre>
242   *
243   * <p>Builder instances can be reused; it is safe to call {@link #build} multiple times to build
244   * multiple multimaps in series. Each multimap contains the key-value mappings in the previously
245   * created multimaps.
246   *
247   * @since 2.0
248   */
249  public static final class Builder<K, V> extends ImmutableMultimap.Builder<K, V> {
250    /**
251     * Creates a new builder. The returned builder is equivalent to the builder generated by {@link
252     * ImmutableSetMultimap#builder}.
253     */
254    public Builder() {
255      super();
256    }
257
258    @Override
259    Collection<V> newMutableValueCollection() {
260      return Platform.preservesInsertionOrderOnAddsSet();
261    }
262
263    /** Adds a key-value mapping to the built multimap if it is not already present. */
264    @CanIgnoreReturnValue
265    @Override
266    public Builder<K, V> put(K key, V value) {
267      super.put(key, value);
268      return this;
269    }
270
271    /**
272     * Adds an entry to the built multimap if it is not already present.
273     *
274     * @since 11.0
275     */
276    @CanIgnoreReturnValue
277    @Override
278    public Builder<K, V> put(Entry<? extends K, ? extends V> entry) {
279      super.put(entry);
280      return this;
281    }
282
283    /**
284     * {@inheritDoc}
285     *
286     * @since 19.0
287     */
288    @CanIgnoreReturnValue
289    @Override
290    public Builder<K, V> putAll(Iterable<? extends Entry<? extends K, ? extends V>> entries) {
291      super.putAll(entries);
292      return this;
293    }
294
295    @CanIgnoreReturnValue
296    @Override
297    public Builder<K, V> putAll(K key, Iterable<? extends V> values) {
298      super.putAll(key, values);
299      return this;
300    }
301
302    @CanIgnoreReturnValue
303    @Override
304    public Builder<K, V> putAll(K key, V... values) {
305      return putAll(key, Arrays.asList(values));
306    }
307
308    @CanIgnoreReturnValue
309    @Override
310    public Builder<K, V> putAll(Multimap<? extends K, ? extends V> multimap) {
311      for (Entry<? extends K, ? extends Collection<? extends V>> entry :
312          multimap.asMap().entrySet()) {
313        putAll(entry.getKey(), entry.getValue());
314      }
315      return this;
316    }
317
318    @CanIgnoreReturnValue
319    @Override
320    Builder<K, V> combine(ImmutableMultimap.Builder<K, V> other) {
321      super.combine(other);
322      return this;
323    }
324
325    /**
326     * {@inheritDoc}
327     *
328     * @since 8.0
329     */
330    @CanIgnoreReturnValue
331    @Override
332    public Builder<K, V> orderKeysBy(Comparator<? super K> keyComparator) {
333      super.orderKeysBy(keyComparator);
334      return this;
335    }
336
337    /**
338     * Specifies the ordering of the generated multimap's values for each key.
339     *
340     * <p>If this method is called, the sets returned by the {@code get()} method of the generated
341     * multimap and its {@link Multimap#asMap()} view are {@link ImmutableSortedSet} instances.
342     * However, serialization does not preserve that property, though it does maintain the key and
343     * value ordering.
344     *
345     * @since 8.0
346     */
347    // TODO: Make serialization behavior consistent.
348    @CanIgnoreReturnValue
349    @Override
350    public Builder<K, V> orderValuesBy(Comparator<? super V> valueComparator) {
351      super.orderValuesBy(valueComparator);
352      return this;
353    }
354
355    /** Returns a newly-created immutable set multimap. */
356    @Override
357    public ImmutableSetMultimap<K, V> build() {
358      Collection<Map.Entry<K, Collection<V>>> mapEntries = builderMap.entrySet();
359      if (keyComparator != null) {
360        mapEntries = Ordering.from(keyComparator).<K>onKeys().immutableSortedCopy(mapEntries);
361      }
362      return fromMapEntries(mapEntries, valueComparator);
363    }
364  }
365
366  /**
367   * Returns an immutable set multimap containing the same mappings as {@code multimap}. The
368   * generated multimap's key and value orderings correspond to the iteration ordering of the {@code
369   * multimap.asMap()} view. Repeated occurrences of an entry in the multimap after the first are
370   * ignored.
371   *
372   * <p>Despite the method name, this method attempts to avoid actually copying the data when it is
373   * safe to do so. The exact circumstances under which a copy will or will not be performed are
374   * undocumented and subject to change.
375   *
376   * @throws NullPointerException if any key or value in {@code multimap} is null
377   */
378  public static <K, V> ImmutableSetMultimap<K, V> copyOf(
379      Multimap<? extends K, ? extends V> multimap) {
380    return copyOf(multimap, null);
381  }
382
383  private static <K, V> ImmutableSetMultimap<K, V> copyOf(
384      Multimap<? extends K, ? extends V> multimap,
385      @CheckForNull Comparator<? super V> valueComparator) {
386    checkNotNull(multimap); // eager for GWT
387    if (multimap.isEmpty() && valueComparator == null) {
388      return of();
389    }
390
391    if (multimap instanceof ImmutableSetMultimap) {
392      @SuppressWarnings("unchecked") // safe since multimap is not writable
393      ImmutableSetMultimap<K, V> kvMultimap = (ImmutableSetMultimap<K, V>) multimap;
394      if (!kvMultimap.isPartialView()) {
395        return kvMultimap;
396      }
397    }
398
399    return fromMapEntries(multimap.asMap().entrySet(), valueComparator);
400  }
401
402  /**
403   * Returns an immutable multimap containing the specified entries. The returned multimap iterates
404   * over keys in the order they were first encountered in the input, and the values for each key
405   * are iterated in the order they were encountered. If two values for the same key are {@linkplain
406   * Object#equals equal}, the first value encountered is used.
407   *
408   * @throws NullPointerException if any key, value, or entry is null
409   * @since 19.0
410   */
411  public static <K, V> ImmutableSetMultimap<K, V> copyOf(
412      Iterable<? extends Entry<? extends K, ? extends V>> entries) {
413    return new Builder<K, V>().putAll(entries).build();
414  }
415
416  /** Creates an ImmutableSetMultimap from an asMap.entrySet. */
417  static <K, V> ImmutableSetMultimap<K, V> fromMapEntries(
418      Collection<? extends Map.Entry<? extends K, ? extends Collection<? extends V>>> mapEntries,
419      @CheckForNull Comparator<? super V> valueComparator) {
420    if (mapEntries.isEmpty()) {
421      return of();
422    }
423    ImmutableMap.Builder<K, ImmutableSet<V>> builder =
424        new ImmutableMap.Builder<>(mapEntries.size());
425    int size = 0;
426
427    for (Entry<? extends K, ? extends Collection<? extends V>> entry : mapEntries) {
428      K key = entry.getKey();
429      Collection<? extends V> values = entry.getValue();
430      ImmutableSet<V> set = valueSet(valueComparator, values);
431      if (!set.isEmpty()) {
432        builder.put(key, set);
433        size += set.size();
434      }
435    }
436
437    return new ImmutableSetMultimap<>(builder.buildOrThrow(), size, valueComparator);
438  }
439
440  /**
441   * Returned by get() when a missing key is provided. Also holds the comparator, if any, used for
442   * values.
443   */
444  private final transient ImmutableSet<V> emptySet;
445
446  ImmutableSetMultimap(
447      ImmutableMap<K, ImmutableSet<V>> map,
448      int size,
449      @CheckForNull Comparator<? super V> valueComparator) {
450    super(map, size);
451    this.emptySet = emptySet(valueComparator);
452  }
453
454  // views
455
456  /**
457   * Returns an immutable set of the values for the given key. If no mappings in the multimap have
458   * the provided key, an empty immutable set is returned. The values are in the same order as the
459   * parameters used to build this multimap.
460   */
461  @Override
462  public ImmutableSet<V> get(K key) {
463    // This cast is safe as its type is known in constructor.
464    ImmutableSet<V> set = (ImmutableSet<V>) map.get(key);
465    return MoreObjects.firstNonNull(set, emptySet);
466  }
467
468  @LazyInit @RetainedWith @CheckForNull private transient ImmutableSetMultimap<V, K> inverse;
469
470  /**
471   * {@inheritDoc}
472   *
473   * <p>Because an inverse of a set multimap cannot contain multiple pairs with the same key and
474   * value, this method returns an {@code ImmutableSetMultimap} rather than the {@code
475   * ImmutableMultimap} specified in the {@code ImmutableMultimap} class.
476   */
477  @Override
478  public ImmutableSetMultimap<V, K> inverse() {
479    ImmutableSetMultimap<V, K> result = inverse;
480    return (result == null) ? (inverse = invert()) : result;
481  }
482
483  private ImmutableSetMultimap<V, K> invert() {
484    Builder<V, K> builder = builder();
485    for (Entry<K, V> entry : entries()) {
486      builder.put(entry.getValue(), entry.getKey());
487    }
488    ImmutableSetMultimap<V, K> invertedMultimap = builder.build();
489    invertedMultimap.inverse = this;
490    return invertedMultimap;
491  }
492
493  /**
494   * Guaranteed to throw an exception and leave the multimap unmodified.
495   *
496   * @throws UnsupportedOperationException always
497   * @deprecated Unsupported operation.
498   */
499  @CanIgnoreReturnValue
500  @Deprecated
501  @Override
502  @DoNotCall("Always throws UnsupportedOperationException")
503  public final ImmutableSet<V> removeAll(@CheckForNull Object key) {
504    throw new UnsupportedOperationException();
505  }
506
507  /**
508   * Guaranteed to throw an exception and leave the multimap unmodified.
509   *
510   * @throws UnsupportedOperationException always
511   * @deprecated Unsupported operation.
512   */
513  @CanIgnoreReturnValue
514  @Deprecated
515  @Override
516  @DoNotCall("Always throws UnsupportedOperationException")
517  public final ImmutableSet<V> replaceValues(K key, Iterable<? extends V> values) {
518    throw new UnsupportedOperationException();
519  }
520
521  @LazyInit @RetainedWith @CheckForNull private transient ImmutableSet<Entry<K, V>> entries;
522
523  /**
524   * Returns an immutable collection of all key-value pairs in the multimap. Its iterator traverses
525   * the values for the first key, the values for the second key, and so on.
526   */
527  @Override
528  public ImmutableSet<Entry<K, V>> entries() {
529    ImmutableSet<Entry<K, V>> result = entries;
530    return result == null ? (entries = new EntrySet<>(this)) : result;
531  }
532
533  private static final class EntrySet<K, V> extends ImmutableSet<Entry<K, V>> {
534    @Weak private final transient ImmutableSetMultimap<K, V> multimap;
535
536    EntrySet(ImmutableSetMultimap<K, V> multimap) {
537      this.multimap = multimap;
538    }
539
540    @Override
541    public boolean contains(@CheckForNull Object object) {
542      if (object instanceof Entry) {
543        Entry<?, ?> entry = (Entry<?, ?>) object;
544        return multimap.containsEntry(entry.getKey(), entry.getValue());
545      }
546      return false;
547    }
548
549    @Override
550    public int size() {
551      return multimap.size();
552    }
553
554    @Override
555    public UnmodifiableIterator<Entry<K, V>> iterator() {
556      return multimap.entryIterator();
557    }
558
559    @Override
560    boolean isPartialView() {
561      return false;
562    }
563
564    // redeclare to help optimizers with b/310253115
565    @SuppressWarnings("RedundantOverride")
566    @Override
567    @J2ktIncompatible // serialization
568    @GwtIncompatible // serialization
569    Object writeReplace() {
570      return super.writeReplace();
571    }
572  }
573
574  private static <V> ImmutableSet<V> valueSet(
575      @CheckForNull Comparator<? super V> valueComparator, Collection<? extends V> values) {
576    return (valueComparator == null)
577        ? ImmutableSet.copyOf(values)
578        : ImmutableSortedSet.copyOf(valueComparator, values);
579  }
580
581  private static <V> ImmutableSet<V> emptySet(@CheckForNull Comparator<? super V> valueComparator) {
582    return (valueComparator == null)
583        ? ImmutableSet.<V>of()
584        : ImmutableSortedSet.<V>emptySet(valueComparator);
585  }
586
587  private static <V> ImmutableSet.Builder<V> valuesBuilder(
588      @CheckForNull Comparator<? super V> valueComparator) {
589    return (valueComparator == null)
590        ? new ImmutableSet.Builder<V>()
591        : new ImmutableSortedSet.Builder<V>(valueComparator);
592  }
593
594  /**
595   * @serialData number of distinct keys, and then for each distinct key: the key, the number of
596   *     values for that key, and the key's values
597   */
598  @GwtIncompatible // java.io.ObjectOutputStream
599  @J2ktIncompatible
600  private void writeObject(ObjectOutputStream stream) throws IOException {
601    stream.defaultWriteObject();
602    stream.writeObject(valueComparator());
603    Serialization.writeMultimap(this, stream);
604  }
605
606  @CheckForNull
607  Comparator<? super V> valueComparator() {
608    return emptySet instanceof ImmutableSortedSet
609        ? ((ImmutableSortedSet<V>) emptySet).comparator()
610        : null;
611  }
612
613  @GwtIncompatible // java serialization
614  @J2ktIncompatible
615  private static final class SetFieldSettersHolder {
616    static final Serialization.FieldSetter<? super ImmutableSetMultimap<?, ?>>
617        EMPTY_SET_FIELD_SETTER =
618            Serialization.getFieldSetter(ImmutableSetMultimap.class, "emptySet");
619  }
620
621  @GwtIncompatible // java.io.ObjectInputStream
622  @J2ktIncompatible
623  // Serialization type safety is at the caller's mercy.
624  @SuppressWarnings("unchecked")
625  private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
626    stream.defaultReadObject();
627    Comparator<Object> valueComparator = (Comparator<Object>) stream.readObject();
628    int keyCount = stream.readInt();
629    if (keyCount < 0) {
630      throw new InvalidObjectException("Invalid key count " + keyCount);
631    }
632    ImmutableMap.Builder<Object, ImmutableSet<Object>> builder = ImmutableMap.builder();
633    int tmpSize = 0;
634
635    for (int i = 0; i < keyCount; i++) {
636      Object key = requireNonNull(stream.readObject());
637      int valueCount = stream.readInt();
638      if (valueCount <= 0) {
639        throw new InvalidObjectException("Invalid value count " + valueCount);
640      }
641
642      ImmutableSet.Builder<Object> valuesBuilder = valuesBuilder(valueComparator);
643      for (int j = 0; j < valueCount; j++) {
644        valuesBuilder.add(requireNonNull(stream.readObject()));
645      }
646      ImmutableSet<Object> valueSet = valuesBuilder.build();
647      if (valueSet.size() != valueCount) {
648        throw new InvalidObjectException("Duplicate key-value pairs exist for key " + key);
649      }
650      builder.put(key, valueSet);
651      tmpSize += valueCount;
652    }
653
654    ImmutableMap<Object, ImmutableSet<Object>> tmpMap;
655    try {
656      tmpMap = builder.buildOrThrow();
657    } catch (IllegalArgumentException e) {
658      throw (InvalidObjectException) new InvalidObjectException(e.getMessage()).initCause(e);
659    }
660
661    FieldSettersHolder.MAP_FIELD_SETTER.set(this, tmpMap);
662    FieldSettersHolder.SIZE_FIELD_SETTER.set(this, tmpSize);
663    SetFieldSettersHolder.EMPTY_SET_FIELD_SETTER.set(this, emptySet(valueComparator));
664  }
665
666  @GwtIncompatible // not needed in emulated source.
667  @J2ktIncompatible
668  private static final long serialVersionUID = 0;
669}