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.GwtCompatible;
023import com.google.common.annotations.GwtIncompatible;
024import com.google.common.annotations.J2ktIncompatible;
025import com.google.common.base.MoreObjects;
026import com.google.errorprone.annotations.CanIgnoreReturnValue;
027import com.google.errorprone.annotations.DoNotCall;
028import com.google.errorprone.annotations.concurrent.LazyInit;
029import com.google.j2objc.annotations.RetainedWith;
030import com.google.j2objc.annotations.Weak;
031import java.io.IOException;
032import java.io.InvalidObjectException;
033import java.io.ObjectInputStream;
034import java.io.ObjectOutputStream;
035import java.util.Arrays;
036import java.util.Collection;
037import java.util.Comparator;
038import java.util.Map;
039import java.util.Map.Entry;
040import java.util.function.Function;
041import java.util.stream.Collector;
042import java.util.stream.Stream;
043import javax.annotation.CheckForNull;
044import org.checkerframework.checker.nullness.qual.Nullable;
045
046/**
047 * A {@link SetMultimap} whose contents will never change, with many other important properties
048 * detailed at {@link ImmutableCollection}.
049 *
050 * <p><b>Warning:</b> As in all {@link SetMultimap}s, do not modify either a key <i>or a value</i>
051 * of a {@code ImmutableSetMultimap} in a way that affects its {@link Object#equals} behavior.
052 * Undefined behavior and bugs will result.
053 *
054 * <p>See the Guava User Guide article on <a href=
055 * "https://github.com/google/guava/wiki/ImmutableCollectionsExplained">immutable collections</a>.
056 *
057 * @author Mike Ward
058 * @since 2.0
059 */
060@GwtCompatible(serializable = true, emulated = true)
061@ElementTypesAreNonnullByDefault
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   * <pre>{@code
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   * }</pre>
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   * <pre>{@code
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   * }</pre>
136   *
137   * @since 21.0
138   */
139  public static <T extends @Nullable Object, K, V>
140      Collector<T, ?, ImmutableSetMultimap<K, V>> flatteningToImmutableSetMultimap(
141          Function<? super T, ? extends K> keyFunction,
142          Function<? super T, ? extends Stream<? extends V>> valuesFunction) {
143    return CollectCollectors.flatteningToImmutableSetMultimap(keyFunction, valuesFunction);
144  }
145
146  /**
147   * Returns the empty multimap.
148   *
149   * <p><b>Performance note:</b> the instance returned is a singleton.
150   */
151  // Casting is safe because the multimap will never hold any elements.
152  @SuppressWarnings("unchecked")
153  public static <K, V> ImmutableSetMultimap<K, V> of() {
154    return (ImmutableSetMultimap<K, V>) EmptyImmutableSetMultimap.INSTANCE;
155  }
156
157  /** Returns an immutable multimap containing a single entry. */
158  public static <K, V> ImmutableSetMultimap<K, V> of(K k1, V v1) {
159    ImmutableSetMultimap.Builder<K, V> builder = ImmutableSetMultimap.builder();
160    builder.put(k1, v1);
161    return builder.build();
162  }
163
164  /**
165   * Returns an immutable multimap containing the given entries, in order. Repeated occurrences of
166   * an entry (according to {@link Object#equals}) after the first are ignored.
167   */
168  public static <K, V> ImmutableSetMultimap<K, V> of(K k1, V v1, K k2, V v2) {
169    ImmutableSetMultimap.Builder<K, V> builder = ImmutableSetMultimap.builder();
170    builder.put(k1, v1);
171    builder.put(k2, v2);
172    return builder.build();
173  }
174
175  /**
176   * Returns an immutable multimap containing the given entries, in order. Repeated occurrences of
177   * an entry (according to {@link Object#equals}) after the first are ignored.
178   */
179  public static <K, V> ImmutableSetMultimap<K, V> of(K k1, V v1, K k2, V v2, K k3, V v3) {
180    ImmutableSetMultimap.Builder<K, V> builder = ImmutableSetMultimap.builder();
181    builder.put(k1, v1);
182    builder.put(k2, v2);
183    builder.put(k3, v3);
184    return builder.build();
185  }
186
187  /**
188   * Returns an immutable multimap containing the given entries, in order. Repeated occurrences of
189   * an entry (according to {@link Object#equals}) after the first are ignored.
190   */
191  public static <K, V> ImmutableSetMultimap<K, V> of(
192      K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4) {
193    ImmutableSetMultimap.Builder<K, V> builder = ImmutableSetMultimap.builder();
194    builder.put(k1, v1);
195    builder.put(k2, v2);
196    builder.put(k3, v3);
197    builder.put(k4, v4);
198    return builder.build();
199  }
200
201  /**
202   * Returns an immutable multimap containing the given entries, in order. Repeated occurrences of
203   * an entry (according to {@link Object#equals}) after the first are ignored.
204   */
205  public static <K, V> ImmutableSetMultimap<K, V> of(
206      K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5) {
207    ImmutableSetMultimap.Builder<K, V> builder = ImmutableSetMultimap.builder();
208    builder.put(k1, v1);
209    builder.put(k2, v2);
210    builder.put(k3, v3);
211    builder.put(k4, v4);
212    builder.put(k5, v5);
213    return builder.build();
214  }
215
216  // looking for of() with > 5 entries? Use the builder instead.
217
218  /** Returns a new {@link Builder}. */
219  public static <K, V> Builder<K, V> builder() {
220    return new Builder<>();
221  }
222
223  /**
224   * A builder for creating immutable {@code SetMultimap} instances, especially {@code public static
225   * final} multimaps ("constant multimaps"). Example:
226   *
227   * <pre>{@code
228   * static final Multimap<String, Integer> STRING_TO_INTEGER_MULTIMAP =
229   *     new ImmutableSetMultimap.Builder<String, Integer>()
230   *         .put("one", 1)
231   *         .putAll("several", 1, 2, 3)
232   *         .putAll("many", 1, 2, 3, 4, 5)
233   *         .build();
234   * }</pre>
235   *
236   * <p>Builder instances can be reused; it is safe to call {@link #build} multiple times to build
237   * multiple multimaps in series. Each multimap contains the key-value mappings in the previously
238   * created multimaps.
239   *
240   * @since 2.0
241   */
242  public static final class Builder<K, V> extends ImmutableMultimap.Builder<K, V> {
243    /**
244     * Creates a new builder. The returned builder is equivalent to the builder generated by {@link
245     * ImmutableSetMultimap#builder}.
246     */
247    public Builder() {
248      super();
249    }
250
251    @Override
252    Collection<V> newMutableValueCollection() {
253      return Platform.preservesInsertionOrderOnAddsSet();
254    }
255
256    /** Adds a key-value mapping to the built multimap if it is not already present. */
257    @CanIgnoreReturnValue
258    @Override
259    public Builder<K, V> put(K key, V value) {
260      super.put(key, value);
261      return this;
262    }
263
264    /**
265     * Adds an entry to the built multimap if it is not already present.
266     *
267     * @since 11.0
268     */
269    @CanIgnoreReturnValue
270    @Override
271    public Builder<K, V> put(Entry<? extends K, ? extends V> entry) {
272      super.put(entry);
273      return this;
274    }
275
276    /**
277     * {@inheritDoc}
278     *
279     * @since 19.0
280     */
281    @CanIgnoreReturnValue
282    @Override
283    public Builder<K, V> putAll(Iterable<? extends Entry<? extends K, ? extends V>> entries) {
284      super.putAll(entries);
285      return this;
286    }
287
288    @CanIgnoreReturnValue
289    @Override
290    public Builder<K, V> putAll(K key, Iterable<? extends V> values) {
291      super.putAll(key, values);
292      return this;
293    }
294
295    @CanIgnoreReturnValue
296    @Override
297    public Builder<K, V> putAll(K key, V... values) {
298      return putAll(key, Arrays.asList(values));
299    }
300
301    @CanIgnoreReturnValue
302    @Override
303    public Builder<K, V> putAll(Multimap<? extends K, ? extends V> multimap) {
304      for (Entry<? extends K, ? extends Collection<? extends V>> entry :
305          multimap.asMap().entrySet()) {
306        putAll(entry.getKey(), entry.getValue());
307      }
308      return this;
309    }
310
311    @CanIgnoreReturnValue
312    @Override
313    Builder<K, V> combine(ImmutableMultimap.Builder<K, V> other) {
314      super.combine(other);
315      return this;
316    }
317
318    /**
319     * {@inheritDoc}
320     *
321     * @since 8.0
322     */
323    @CanIgnoreReturnValue
324    @Override
325    public Builder<K, V> orderKeysBy(Comparator<? super K> keyComparator) {
326      super.orderKeysBy(keyComparator);
327      return this;
328    }
329
330    /**
331     * Specifies the ordering of the generated multimap's values for each key.
332     *
333     * <p>If this method is called, the sets returned by the {@code get()} method of the generated
334     * multimap and its {@link Multimap#asMap()} view are {@link ImmutableSortedSet} instances.
335     * However, serialization does not preserve that property, though it does maintain the key and
336     * value ordering.
337     *
338     * @since 8.0
339     */
340    // TODO: Make serialization behavior consistent.
341    @CanIgnoreReturnValue
342    @Override
343    public Builder<K, V> orderValuesBy(Comparator<? super V> valueComparator) {
344      super.orderValuesBy(valueComparator);
345      return this;
346    }
347
348    /** Returns a newly-created immutable set multimap. */
349    @Override
350    public ImmutableSetMultimap<K, V> build() {
351      Collection<Map.Entry<K, Collection<V>>> mapEntries = builderMap.entrySet();
352      if (keyComparator != null) {
353        mapEntries = Ordering.from(keyComparator).<K>onKeys().immutableSortedCopy(mapEntries);
354      }
355      return fromMapEntries(mapEntries, valueComparator);
356    }
357  }
358
359  /**
360   * Returns an immutable set multimap containing the same mappings as {@code multimap}. The
361   * generated multimap's key and value orderings correspond to the iteration ordering of the {@code
362   * multimap.asMap()} view. Repeated occurrences of an entry in the multimap after the first are
363   * ignored.
364   *
365   * <p>Despite the method name, this method attempts to avoid actually copying the data when it is
366   * safe to do so. The exact circumstances under which a copy will or will not be performed are
367   * undocumented and subject to change.
368   *
369   * @throws NullPointerException if any key or value in {@code multimap} is null
370   */
371  public static <K, V> ImmutableSetMultimap<K, V> copyOf(
372      Multimap<? extends K, ? extends V> multimap) {
373    return copyOf(multimap, null);
374  }
375
376  private static <K, V> ImmutableSetMultimap<K, V> copyOf(
377      Multimap<? extends K, ? extends V> multimap,
378      @CheckForNull Comparator<? super V> valueComparator) {
379    checkNotNull(multimap); // eager for GWT
380    if (multimap.isEmpty() && valueComparator == null) {
381      return of();
382    }
383
384    if (multimap instanceof ImmutableSetMultimap) {
385      @SuppressWarnings("unchecked") // safe since multimap is not writable
386      ImmutableSetMultimap<K, V> kvMultimap = (ImmutableSetMultimap<K, V>) multimap;
387      if (!kvMultimap.isPartialView()) {
388        return kvMultimap;
389      }
390    }
391
392    return fromMapEntries(multimap.asMap().entrySet(), valueComparator);
393  }
394
395  /**
396   * Returns an immutable multimap containing the specified entries. The returned multimap iterates
397   * over keys in the order they were first encountered in the input, and the values for each key
398   * are iterated in the order they were encountered. If two values for the same key are {@linkplain
399   * Object#equals equal}, the first value encountered is used.
400   *
401   * @throws NullPointerException if any key, value, or entry is null
402   * @since 19.0
403   */
404  public static <K, V> ImmutableSetMultimap<K, V> copyOf(
405      Iterable<? extends Entry<? extends K, ? extends V>> entries) {
406    return new Builder<K, V>().putAll(entries).build();
407  }
408
409  /** Creates an ImmutableSetMultimap from an asMap.entrySet. */
410  static <K, V> ImmutableSetMultimap<K, V> fromMapEntries(
411      Collection<? extends Map.Entry<? extends K, ? extends Collection<? extends V>>> mapEntries,
412      @CheckForNull Comparator<? super V> valueComparator) {
413    if (mapEntries.isEmpty()) {
414      return of();
415    }
416    ImmutableMap.Builder<K, ImmutableSet<V>> builder =
417        new ImmutableMap.Builder<>(mapEntries.size());
418    int size = 0;
419
420    for (Entry<? extends K, ? extends Collection<? extends V>> entry : mapEntries) {
421      K key = entry.getKey();
422      Collection<? extends V> values = entry.getValue();
423      ImmutableSet<V> set = valueSet(valueComparator, values);
424      if (!set.isEmpty()) {
425        builder.put(key, set);
426        size += set.size();
427      }
428    }
429
430    return new ImmutableSetMultimap<>(builder.buildOrThrow(), size, valueComparator);
431  }
432
433  /**
434   * Returned by get() when a missing key is provided. Also holds the comparator, if any, used for
435   * values.
436   */
437  private final transient ImmutableSet<V> emptySet;
438
439  ImmutableSetMultimap(
440      ImmutableMap<K, ImmutableSet<V>> map,
441      int size,
442      @CheckForNull Comparator<? super V> valueComparator) {
443    super(map, size);
444    this.emptySet = emptySet(valueComparator);
445  }
446
447  // views
448
449  /**
450   * Returns an immutable set of the values for the given key. If no mappings in the multimap have
451   * the provided key, an empty immutable set is returned. The values are in the same order as the
452   * parameters used to build this multimap.
453   */
454  @Override
455  public ImmutableSet<V> get(K key) {
456    // This cast is safe as its type is known in constructor.
457    ImmutableSet<V> set = (ImmutableSet<V>) map.get(key);
458    return MoreObjects.firstNonNull(set, emptySet);
459  }
460
461  @LazyInit @RetainedWith @CheckForNull private transient ImmutableSetMultimap<V, K> inverse;
462
463  /**
464   * {@inheritDoc}
465   *
466   * <p>Because an inverse of a set multimap cannot contain multiple pairs with the same key and
467   * value, this method returns an {@code ImmutableSetMultimap} rather than the {@code
468   * ImmutableMultimap} specified in the {@code ImmutableMultimap} class.
469   */
470  @Override
471  public ImmutableSetMultimap<V, K> inverse() {
472    ImmutableSetMultimap<V, K> result = inverse;
473    return (result == null) ? (inverse = invert()) : result;
474  }
475
476  private ImmutableSetMultimap<V, K> invert() {
477    Builder<V, K> builder = builder();
478    for (Entry<K, V> entry : entries()) {
479      builder.put(entry.getValue(), entry.getKey());
480    }
481    ImmutableSetMultimap<V, K> invertedMultimap = builder.build();
482    invertedMultimap.inverse = this;
483    return invertedMultimap;
484  }
485
486  /**
487   * Guaranteed to throw an exception and leave the multimap unmodified.
488   *
489   * @throws UnsupportedOperationException always
490   * @deprecated Unsupported operation.
491   */
492  @CanIgnoreReturnValue
493  @Deprecated
494  @Override
495  @DoNotCall("Always throws UnsupportedOperationException")
496  public final ImmutableSet<V> removeAll(@CheckForNull Object key) {
497    throw new UnsupportedOperationException();
498  }
499
500  /**
501   * Guaranteed to throw an exception and leave the multimap unmodified.
502   *
503   * @throws UnsupportedOperationException always
504   * @deprecated Unsupported operation.
505   */
506  @CanIgnoreReturnValue
507  @Deprecated
508  @Override
509  @DoNotCall("Always throws UnsupportedOperationException")
510  public final ImmutableSet<V> replaceValues(K key, Iterable<? extends V> values) {
511    throw new UnsupportedOperationException();
512  }
513
514  @LazyInit @RetainedWith @CheckForNull private transient ImmutableSet<Entry<K, V>> entries;
515
516  /**
517   * Returns an immutable collection of all key-value pairs in the multimap. Its iterator traverses
518   * the values for the first key, the values for the second key, and so on.
519   */
520  @Override
521  public ImmutableSet<Entry<K, V>> entries() {
522    ImmutableSet<Entry<K, V>> result = entries;
523    return result == null ? (entries = new EntrySet<>(this)) : result;
524  }
525
526  private static final class EntrySet<K, V> extends ImmutableSet<Entry<K, V>> {
527    @Weak private final transient ImmutableSetMultimap<K, V> multimap;
528
529    EntrySet(ImmutableSetMultimap<K, V> multimap) {
530      this.multimap = multimap;
531    }
532
533    @Override
534    public boolean contains(@CheckForNull Object object) {
535      if (object instanceof Entry) {
536        Entry<?, ?> entry = (Entry<?, ?>) object;
537        return multimap.containsEntry(entry.getKey(), entry.getValue());
538      }
539      return false;
540    }
541
542    @Override
543    public int size() {
544      return multimap.size();
545    }
546
547    @Override
548    public UnmodifiableIterator<Entry<K, V>> iterator() {
549      return multimap.entryIterator();
550    }
551
552    @Override
553    boolean isPartialView() {
554      return false;
555    }
556
557    // redeclare to help optimizers with b/310253115
558    @SuppressWarnings("RedundantOverride")
559    @Override
560    @J2ktIncompatible // serialization
561    @GwtIncompatible // serialization
562    Object writeReplace() {
563      return super.writeReplace();
564    }
565  }
566
567  private static <V> ImmutableSet<V> valueSet(
568      @CheckForNull Comparator<? super V> valueComparator, Collection<? extends V> values) {
569    return (valueComparator == null)
570        ? ImmutableSet.copyOf(values)
571        : ImmutableSortedSet.copyOf(valueComparator, values);
572  }
573
574  private static <V> ImmutableSet<V> emptySet(@CheckForNull Comparator<? super V> valueComparator) {
575    return (valueComparator == null)
576        ? ImmutableSet.<V>of()
577        : ImmutableSortedSet.<V>emptySet(valueComparator);
578  }
579
580  private static <V> ImmutableSet.Builder<V> valuesBuilder(
581      @CheckForNull Comparator<? super V> valueComparator) {
582    return (valueComparator == null)
583        ? new ImmutableSet.Builder<V>()
584        : new ImmutableSortedSet.Builder<V>(valueComparator);
585  }
586
587  /**
588   * @serialData number of distinct keys, and then for each distinct key: the key, the number of
589   *     values for that key, and the key's values
590   */
591  @GwtIncompatible // java.io.ObjectOutputStream
592  @J2ktIncompatible
593  private void writeObject(ObjectOutputStream stream) throws IOException {
594    stream.defaultWriteObject();
595    stream.writeObject(valueComparator());
596    Serialization.writeMultimap(this, stream);
597  }
598
599  @CheckForNull
600  Comparator<? super V> valueComparator() {
601    return emptySet instanceof ImmutableSortedSet
602        ? ((ImmutableSortedSet<V>) emptySet).comparator()
603        : null;
604  }
605
606  @GwtIncompatible // java serialization
607  @J2ktIncompatible
608  private static final class SetFieldSettersHolder {
609    static final Serialization.FieldSetter<ImmutableSetMultimap> EMPTY_SET_FIELD_SETTER =
610        Serialization.getFieldSetter(ImmutableSetMultimap.class, "emptySet");
611  }
612
613  @GwtIncompatible // java.io.ObjectInputStream
614  @J2ktIncompatible
615  // Serialization type safety is at the caller's mercy.
616  @SuppressWarnings("unchecked")
617  private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
618    stream.defaultReadObject();
619    Comparator<Object> valueComparator = (Comparator<Object>) stream.readObject();
620    int keyCount = stream.readInt();
621    if (keyCount < 0) {
622      throw new InvalidObjectException("Invalid key count " + keyCount);
623    }
624    ImmutableMap.Builder<Object, ImmutableSet<Object>> builder = ImmutableMap.builder();
625    int tmpSize = 0;
626
627    for (int i = 0; i < keyCount; i++) {
628      Object key = requireNonNull(stream.readObject());
629      int valueCount = stream.readInt();
630      if (valueCount <= 0) {
631        throw new InvalidObjectException("Invalid value count " + valueCount);
632      }
633
634      ImmutableSet.Builder<Object> valuesBuilder = valuesBuilder(valueComparator);
635      for (int j = 0; j < valueCount; j++) {
636        valuesBuilder.add(requireNonNull(stream.readObject()));
637      }
638      ImmutableSet<Object> valueSet = valuesBuilder.build();
639      if (valueSet.size() != valueCount) {
640        throw new InvalidObjectException("Duplicate key-value pairs exist for key " + key);
641      }
642      builder.put(key, valueSet);
643      tmpSize += valueCount;
644    }
645
646    ImmutableMap<Object, ImmutableSet<Object>> tmpMap;
647    try {
648      tmpMap = builder.buildOrThrow();
649    } catch (IllegalArgumentException e) {
650      throw (InvalidObjectException) new InvalidObjectException(e.getMessage()).initCause(e);
651    }
652
653    FieldSettersHolder.MAP_FIELD_SETTER.set(this, tmpMap);
654    FieldSettersHolder.SIZE_FIELD_SETTER.set(this, tmpSize);
655    SetFieldSettersHolder.EMPTY_SET_FIELD_SETTER.set(this, emptySet(valueComparator));
656  }
657
658  @GwtIncompatible // not needed in emulated source.
659  @J2ktIncompatible
660  private static final long serialVersionUID = 0;
661}