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