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.qual.MonotonicNonNull;
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>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      @Nullable 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      @Nullable 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(@Nullable 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 @MonotonicNonNull @RetainedWith private transient ImmutableSetMultimap<V, K> inverse;
467
468  /**
469   * {@inheritDoc}
470   *
471   * <p>Because an inverse of a set multimap cannot contain multiple pairs with the same key and
472   * value, this method returns an {@code ImmutableSetMultimap} rather than the {@code
473   * ImmutableMultimap} specified in the {@code ImmutableMultimap} class.
474   *
475   * @since 11.0
476   */
477  public ImmutableSetMultimap<V, K> inverse() {
478    ImmutableSetMultimap<V, K> result = inverse;
479    return (result == null) ? (inverse = invert()) : result;
480  }
481
482  private ImmutableSetMultimap<V, K> invert() {
483    Builder<V, K> builder = builder();
484    for (Entry<K, V> entry : entries()) {
485      builder.put(entry.getValue(), entry.getKey());
486    }
487    ImmutableSetMultimap<V, K> invertedMultimap = builder.build();
488    invertedMultimap.inverse = this;
489    return invertedMultimap;
490  }
491
492  /**
493   * Guaranteed to throw an exception and leave the multimap unmodified.
494   *
495   * @throws UnsupportedOperationException always
496   * @deprecated Unsupported operation.
497   */
498  @CanIgnoreReturnValue
499  @Deprecated
500  @Override
501  public ImmutableSet<V> removeAll(Object key) {
502    throw new UnsupportedOperationException();
503  }
504
505  /**
506   * Guaranteed to throw an exception and leave the multimap unmodified.
507   *
508   * @throws UnsupportedOperationException always
509   * @deprecated Unsupported operation.
510   */
511  @CanIgnoreReturnValue
512  @Deprecated
513  @Override
514  public ImmutableSet<V> replaceValues(K key, Iterable<? extends V> values) {
515    throw new UnsupportedOperationException();
516  }
517
518  private transient @MonotonicNonNull ImmutableSet<Entry<K, V>> entries;
519
520  /**
521   * Returns an immutable collection of all key-value pairs in the multimap. Its iterator traverses
522   * the values for the first key, the values for the second key, and so on.
523   */
524  @Override
525  public ImmutableSet<Entry<K, V>> entries() {
526    ImmutableSet<Entry<K, V>> result = entries;
527    return result == null ? (entries = new EntrySet<>(this)) : result;
528  }
529
530  private static final class EntrySet<K, V> extends ImmutableSet<Entry<K, V>> {
531    @Weak private final transient ImmutableSetMultimap<K, V> multimap;
532
533    EntrySet(ImmutableSetMultimap<K, V> multimap) {
534      this.multimap = multimap;
535    }
536
537    @Override
538    public boolean contains(@Nullable Object object) {
539      if (object instanceof Entry) {
540        Entry<?, ?> entry = (Entry<?, ?>) object;
541        return multimap.containsEntry(entry.getKey(), entry.getValue());
542      }
543      return false;
544    }
545
546    @Override
547    public int size() {
548      return multimap.size();
549    }
550
551    @Override
552    public UnmodifiableIterator<Entry<K, V>> iterator() {
553      return multimap.entryIterator();
554    }
555
556    @Override
557    boolean isPartialView() {
558      return false;
559    }
560  }
561
562  private static <V> ImmutableSet<V> valueSet(
563      @Nullable Comparator<? super V> valueComparator, Collection<? extends V> values) {
564    return (valueComparator == null)
565        ? ImmutableSet.copyOf(values)
566        : ImmutableSortedSet.copyOf(valueComparator, values);
567  }
568
569  private static <V> ImmutableSet<V> emptySet(@Nullable Comparator<? super V> valueComparator) {
570    return (valueComparator == null)
571        ? ImmutableSet.<V>of()
572        : ImmutableSortedSet.<V>emptySet(valueComparator);
573  }
574
575  private static <V> ImmutableSet.Builder<V> valuesBuilder(
576      @Nullable Comparator<? super V> valueComparator) {
577    return (valueComparator == null)
578        ? new ImmutableSet.Builder<V>()
579        : new ImmutableSortedSet.Builder<V>(valueComparator);
580  }
581
582  /**
583   * @serialData number of distinct keys, and then for each distinct key: the key, the number of
584   *     values for that key, and the key's values
585   */
586  @GwtIncompatible // java.io.ObjectOutputStream
587  private void writeObject(ObjectOutputStream stream) throws IOException {
588    stream.defaultWriteObject();
589    stream.writeObject(valueComparator());
590    Serialization.writeMultimap(this, stream);
591  }
592
593  @Nullable
594  Comparator<? super V> valueComparator() {
595    return emptySet instanceof ImmutableSortedSet
596        ? ((ImmutableSortedSet<V>) emptySet).comparator()
597        : null;
598  }
599  
600  @GwtIncompatible // java serialization
601  private static final class SetFieldSettersHolder {
602    static final Serialization.FieldSetter<ImmutableSetMultimap> EMPTY_SET_FIELD_SETTER =
603        Serialization.getFieldSetter(ImmutableSetMultimap.class, "emptySet");
604  }
605
606  @GwtIncompatible // java.io.ObjectInputStream
607  // Serialization type safety is at the caller's mercy.
608  @SuppressWarnings("unchecked")
609  private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
610    stream.defaultReadObject();
611    Comparator<Object> valueComparator = (Comparator<Object>) stream.readObject();
612    int keyCount = stream.readInt();
613    if (keyCount < 0) {
614      throw new InvalidObjectException("Invalid key count " + keyCount);
615    }
616    ImmutableMap.Builder<Object, ImmutableSet<Object>> builder = ImmutableMap.builder();
617    int tmpSize = 0;
618
619    for (int i = 0; i < keyCount; i++) {
620      Object key = stream.readObject();
621      int valueCount = stream.readInt();
622      if (valueCount <= 0) {
623        throw new InvalidObjectException("Invalid value count " + valueCount);
624      }
625
626      ImmutableSet.Builder<Object> valuesBuilder = valuesBuilder(valueComparator);
627      for (int j = 0; j < valueCount; j++) {
628        valuesBuilder.add(stream.readObject());
629      }
630      ImmutableSet<Object> valueSet = valuesBuilder.build();
631      if (valueSet.size() != valueCount) {
632        throw new InvalidObjectException("Duplicate key-value pairs exist for key " + key);
633      }
634      builder.put(key, valueSet);
635      tmpSize += valueCount;
636    }
637
638    ImmutableMap<Object, ImmutableSet<Object>> tmpMap;
639    try {
640      tmpMap = builder.build();
641    } catch (IllegalArgumentException e) {
642      throw (InvalidObjectException) new InvalidObjectException(e.getMessage()).initCause(e);
643    }
644
645    FieldSettersHolder.MAP_FIELD_SETTER.set(this, tmpMap);
646    FieldSettersHolder.SIZE_FIELD_SETTER.set(this, tmpSize);
647    SetFieldSettersHolder.EMPTY_SET_FIELD_SETTER.set(this, emptySet(valueComparator));
648  }
649
650  @GwtIncompatible // not needed in emulated source.
651  private static final long serialVersionUID = 0;
652}