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