• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2009 The Guava Authors
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package com.google.common.collect;
18 
19 import static com.google.common.base.Preconditions.checkNotNull;
20 
21 import com.google.common.annotations.Beta;
22 import com.google.common.annotations.GwtCompatible;
23 import com.google.common.annotations.GwtIncompatible;
24 import com.google.common.base.MoreObjects;
25 import com.google.errorprone.annotations.CanIgnoreReturnValue;
26 import com.google.errorprone.annotations.DoNotCall;
27 import com.google.errorprone.annotations.concurrent.LazyInit;
28 import com.google.j2objc.annotations.RetainedWith;
29 import com.google.j2objc.annotations.Weak;
30 import java.io.IOException;
31 import java.io.InvalidObjectException;
32 import java.io.ObjectInputStream;
33 import java.io.ObjectOutputStream;
34 import java.util.Arrays;
35 import java.util.Collection;
36 import java.util.Comparator;
37 import java.util.Map;
38 import java.util.Map.Entry;
39 import java.util.function.Function;
40 import java.util.stream.Collector;
41 import java.util.stream.Stream;
42 import javax.annotation.CheckForNull;
43 import org.checkerframework.checker.nullness.qual.Nullable;
44 
45 /**
46  * A {@link SetMultimap} whose contents will never change, with many other important properties
47  * detailed at {@link ImmutableCollection}.
48  *
49  * <p><b>Warning:</b> As in all {@link SetMultimap}s, do not modify either a key <i>or a value</i>
50  * of a {@code ImmutableSetMultimap} in a way that affects its {@link Object#equals} behavior.
51  * Undefined behavior and bugs will result.
52  *
53  * <p>See the Guava User Guide article on <a href=
54  * "https://github.com/google/guava/wiki/ImmutableCollectionsExplained">immutable collections</a>.
55  *
56  * @author Mike Ward
57  * @since 2.0
58  */
59 @GwtCompatible(serializable = true, emulated = true)
60 @ElementTypesAreNonnullByDefault
61 public class ImmutableSetMultimap<K, V> extends ImmutableMultimap<K, V>
62     implements SetMultimap<K, V> {
63   /**
64    * Returns a {@link Collector} that accumulates elements into an {@code ImmutableSetMultimap}
65    * whose keys and values are the result of applying the provided mapping functions to the input
66    * elements.
67    *
68    * <p>For streams with defined encounter order (as defined in the Ordering section of the {@link
69    * java.util.stream} Javadoc), that order is preserved, but entries are <a
70    * href="ImmutableMultimap.html#iteration">grouped by key</a>.
71    *
72    * <p>Example:
73    *
74    * <pre>{@code
75    * static final Multimap<Character, String> FIRST_LETTER_MULTIMAP =
76    *     Stream.of("banana", "apple", "carrot", "asparagus", "cherry")
77    *         .collect(toImmutableSetMultimap(str -> str.charAt(0), str -> str.substring(1)));
78    *
79    * // is equivalent to
80    *
81    * static final Multimap<Character, String> FIRST_LETTER_MULTIMAP =
82    *     new ImmutableSetMultimap.Builder<Character, String>()
83    *         .put('b', "anana")
84    *         .putAll('a', "pple", "sparagus")
85    *         .putAll('c', "arrot", "herry")
86    *         .build();
87    * }</pre>
88    *
89    * @since 21.0
90    */
91   public static <T extends @Nullable Object, K, V>
toImmutableSetMultimap( Function<? super T, ? extends K> keyFunction, Function<? super T, ? extends V> valueFunction)92       Collector<T, ?, ImmutableSetMultimap<K, V>> toImmutableSetMultimap(
93           Function<? super T, ? extends K> keyFunction,
94           Function<? super T, ? extends V> valueFunction) {
95     return CollectCollectors.toImmutableSetMultimap(keyFunction, valueFunction);
96   }
97 
98   /**
99    * Returns a {@code Collector} accumulating entries into an {@code ImmutableSetMultimap}. Each
100    * input element is mapped to a key and a stream of values, each of which are put into the
101    * resulting {@code Multimap}, in the encounter order of the stream and the encounter order of the
102    * streams of values.
103    *
104    * <p>Example:
105    *
106    * <pre>{@code
107    * static final ImmutableSetMultimap<Character, Character> FIRST_LETTER_MULTIMAP =
108    *     Stream.of("banana", "apple", "carrot", "asparagus", "cherry")
109    *         .collect(
110    *             flatteningToImmutableSetMultimap(
111    *                  str -> str.charAt(0),
112    *                  str -> str.substring(1).chars().mapToObj(c -> (char) c));
113    *
114    * // is equivalent to
115    *
116    * static final ImmutableSetMultimap<Character, Character> FIRST_LETTER_MULTIMAP =
117    *     ImmutableSetMultimap.<Character, Character>builder()
118    *         .putAll('b', Arrays.asList('a', 'n', 'a', 'n', 'a'))
119    *         .putAll('a', Arrays.asList('p', 'p', 'l', 'e'))
120    *         .putAll('c', Arrays.asList('a', 'r', 'r', 'o', 't'))
121    *         .putAll('a', Arrays.asList('s', 'p', 'a', 'r', 'a', 'g', 'u', 's'))
122    *         .putAll('c', Arrays.asList('h', 'e', 'r', 'r', 'y'))
123    *         .build();
124    *
125    * // after deduplication, the resulting multimap is equivalent to
126    *
127    * static final ImmutableSetMultimap<Character, Character> FIRST_LETTER_MULTIMAP =
128    *     ImmutableSetMultimap.<Character, Character>builder()
129    *         .putAll('b', Arrays.asList('a', 'n'))
130    *         .putAll('a', Arrays.asList('p', 'l', 'e', 's', 'a', 'r', 'g', 'u'))
131    *         .putAll('c', Arrays.asList('a', 'r', 'o', 't', 'h', 'e', 'y'))
132    *         .build();
133    * }
134    * }</pre>
135    *
136    * @since 21.0
137    */
138   public static <T extends @Nullable Object, K, V>
flatteningToImmutableSetMultimap( Function<? super T, ? extends K> keyFunction, Function<? super T, ? extends Stream<? extends V>> valuesFunction)139       Collector<T, ?, ImmutableSetMultimap<K, V>> flatteningToImmutableSetMultimap(
140           Function<? super T, ? extends K> keyFunction,
141           Function<? super T, ? extends Stream<? extends V>> valuesFunction) {
142     return CollectCollectors.flatteningToImmutableSetMultimap(keyFunction, valuesFunction);
143   }
144 
145   /**
146    * Returns the empty multimap.
147    *
148    * <p><b>Performance note:</b> the instance returned is a singleton.
149    */
150   // Casting is safe because the multimap will never hold any elements.
151   @SuppressWarnings("unchecked")
of()152   public static <K, V> ImmutableSetMultimap<K, V> of() {
153     return (ImmutableSetMultimap<K, V>) EmptyImmutableSetMultimap.INSTANCE;
154   }
155 
156   /** Returns an immutable multimap containing a single entry. */
of(K k1, V v1)157   public static <K, V> ImmutableSetMultimap<K, V> of(K k1, V v1) {
158     ImmutableSetMultimap.Builder<K, V> builder = ImmutableSetMultimap.builder();
159     builder.put(k1, v1);
160     return builder.build();
161   }
162 
163   /**
164    * Returns an immutable multimap containing the given entries, in order. Repeated occurrences of
165    * an entry (according to {@link Object#equals}) after the first are ignored.
166    */
of(K k1, V v1, K k2, V v2)167   public static <K, V> ImmutableSetMultimap<K, V> of(K k1, V v1, K k2, V v2) {
168     ImmutableSetMultimap.Builder<K, V> builder = ImmutableSetMultimap.builder();
169     builder.put(k1, v1);
170     builder.put(k2, v2);
171     return builder.build();
172   }
173 
174   /**
175    * Returns an immutable multimap containing the given entries, in order. Repeated occurrences of
176    * an entry (according to {@link Object#equals}) after the first are ignored.
177    */
of(K k1, V v1, K k2, V v2, K k3, V v3)178   public static <K, V> ImmutableSetMultimap<K, V> of(K k1, V v1, K k2, V v2, K k3, V v3) {
179     ImmutableSetMultimap.Builder<K, V> builder = ImmutableSetMultimap.builder();
180     builder.put(k1, v1);
181     builder.put(k2, v2);
182     builder.put(k3, v3);
183     return builder.build();
184   }
185 
186   /**
187    * Returns an immutable multimap containing the given entries, in order. Repeated occurrences of
188    * an entry (according to {@link Object#equals}) after the first are ignored.
189    */
of( K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4)190   public static <K, V> ImmutableSetMultimap<K, V> of(
191       K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4) {
192     ImmutableSetMultimap.Builder<K, V> builder = ImmutableSetMultimap.builder();
193     builder.put(k1, v1);
194     builder.put(k2, v2);
195     builder.put(k3, v3);
196     builder.put(k4, v4);
197     return builder.build();
198   }
199 
200   /**
201    * Returns an immutable multimap containing the given entries, in order. Repeated occurrences of
202    * an entry (according to {@link Object#equals}) after the first are ignored.
203    */
of( K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5)204   public static <K, V> ImmutableSetMultimap<K, V> of(
205       K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5) {
206     ImmutableSetMultimap.Builder<K, V> builder = ImmutableSetMultimap.builder();
207     builder.put(k1, v1);
208     builder.put(k2, v2);
209     builder.put(k3, v3);
210     builder.put(k4, v4);
211     builder.put(k5, v5);
212     return builder.build();
213   }
214 
215   // looking for of() with > 5 entries? Use the builder instead.
216 
217   /** Returns a new {@link Builder}. */
builder()218   public static <K, V> Builder<K, V> builder() {
219     return new Builder<>();
220   }
221 
222   /**
223    * A builder for creating immutable {@code SetMultimap} instances, especially {@code public static
224    * final} multimaps ("constant multimaps"). Example:
225    *
226    * <pre>{@code
227    * static final Multimap<String, Integer> STRING_TO_INTEGER_MULTIMAP =
228    *     new ImmutableSetMultimap.Builder<String, Integer>()
229    *         .put("one", 1)
230    *         .putAll("several", 1, 2, 3)
231    *         .putAll("many", 1, 2, 3, 4, 5)
232    *         .build();
233    * }</pre>
234    *
235    * <p>Builder instances can be reused; it is safe to call {@link #build} multiple times to build
236    * multiple multimaps in series. Each multimap contains the key-value mappings in the previously
237    * created multimaps.
238    *
239    * @since 2.0
240    */
241   public static final class Builder<K, V> extends ImmutableMultimap.Builder<K, V> {
242     /**
243      * Creates a new builder. The returned builder is equivalent to the builder generated by {@link
244      * ImmutableSetMultimap#builder}.
245      */
Builder()246     public Builder() {
247       super();
248     }
249 
250     @Override
newMutableValueCollection()251     Collection<V> newMutableValueCollection() {
252       return Platform.preservesInsertionOrderOnAddsSet();
253     }
254 
255     /** Adds a key-value mapping to the built multimap if it is not already present. */
256     @CanIgnoreReturnValue
257     @Override
put(K key, V value)258     public Builder<K, V> put(K key, V value) {
259       super.put(key, value);
260       return this;
261     }
262 
263     /**
264      * Adds an entry to the built multimap if it is not already present.
265      *
266      * @since 11.0
267      */
268     @CanIgnoreReturnValue
269     @Override
put(Entry<? extends K, ? extends V> entry)270     public Builder<K, V> put(Entry<? extends K, ? extends V> entry) {
271       super.put(entry);
272       return this;
273     }
274 
275     /**
276      * {@inheritDoc}
277      *
278      * @since 19.0
279      */
280     @CanIgnoreReturnValue
281     @Beta
282     @Override
putAll(Iterable<? extends Entry<? extends K, ? extends V>> entries)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
putAll(K key, Iterable<? extends V> values)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
putAll(K key, V... values)297     public Builder<K, V> putAll(K key, V... values) {
298       return putAll(key, Arrays.asList(values));
299     }
300 
301     @CanIgnoreReturnValue
302     @Override
putAll(Multimap<? extends K, ? extends V> multimap)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
combine(ImmutableMultimap.Builder<K, V> other)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
orderKeysBy(Comparator<? super K> keyComparator)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
orderValuesBy(Comparator<? super V> valueComparator)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
build()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    */
copyOf( Multimap<? extends K, ? extends V> multimap)371   public static <K, V> ImmutableSetMultimap<K, V> copyOf(
372       Multimap<? extends K, ? extends V> multimap) {
373     return copyOf(multimap, null);
374   }
375 
copyOf( Multimap<? extends K, ? extends V> multimap, @CheckForNull Comparator<? super V> valueComparator)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   @Beta
copyOf( Iterable<? extends Entry<? extends K, ? extends V>> entries)405   public static <K, V> ImmutableSetMultimap<K, V> copyOf(
406       Iterable<? extends Entry<? extends K, ? extends V>> entries) {
407     return new Builder<K, V>().putAll(entries).build();
408   }
409 
410   /** Creates an ImmutableSetMultimap from an asMap.entrySet. */
fromMapEntries( Collection<? extends Map.Entry<? extends K, ? extends Collection<? extends V>>> mapEntries, @CheckForNull Comparator<? super V> valueComparator)411   static <K, V> ImmutableSetMultimap<K, V> fromMapEntries(
412       Collection<? extends Map.Entry<? extends K, ? extends Collection<? extends V>>> mapEntries,
413       @CheckForNull Comparator<? super V> valueComparator) {
414     if (mapEntries.isEmpty()) {
415       return of();
416     }
417     ImmutableMap.Builder<K, ImmutableSet<V>> builder =
418         new ImmutableMap.Builder<>(mapEntries.size());
419     int size = 0;
420 
421     for (Entry<? extends K, ? extends Collection<? extends V>> entry : mapEntries) {
422       K key = entry.getKey();
423       Collection<? extends V> values = entry.getValue();
424       ImmutableSet<V> set = valueSet(valueComparator, values);
425       if (!set.isEmpty()) {
426         builder.put(key, set);
427         size += set.size();
428       }
429     }
430 
431     return new ImmutableSetMultimap<>(builder.buildOrThrow(), size, valueComparator);
432   }
433 
434   /**
435    * Returned by get() when a missing key is provided. Also holds the comparator, if any, used for
436    * values.
437    */
438   private final transient ImmutableSet<V> emptySet;
439 
ImmutableSetMultimap( ImmutableMap<K, ImmutableSet<V>> map, int size, @CheckForNull Comparator<? super V> valueComparator)440   ImmutableSetMultimap(
441       ImmutableMap<K, ImmutableSet<V>> map,
442       int size,
443       @CheckForNull Comparator<? super V> valueComparator) {
444     super(map, size);
445     this.emptySet = emptySet(valueComparator);
446   }
447 
448   // views
449 
450   /**
451    * Returns an immutable set of the values for the given key. If no mappings in the multimap have
452    * the provided key, an empty immutable set is returned. The values are in the same order as the
453    * parameters used to build this multimap.
454    */
455   @Override
get(K key)456   public ImmutableSet<V> get(K key) {
457     // This cast is safe as its type is known in constructor.
458     ImmutableSet<V> set = (ImmutableSet<V>) map.get(key);
459     return MoreObjects.firstNonNull(set, emptySet);
460   }
461 
462   @LazyInit @RetainedWith @CheckForNull private transient ImmutableSetMultimap<V, K> inverse;
463 
464   /**
465    * {@inheritDoc}
466    *
467    * <p>Because an inverse of a set multimap cannot contain multiple pairs with the same key and
468    * value, this method returns an {@code ImmutableSetMultimap} rather than the {@code
469    * ImmutableMultimap} specified in the {@code ImmutableMultimap} class.
470    */
471   @Override
inverse()472   public ImmutableSetMultimap<V, K> inverse() {
473     ImmutableSetMultimap<V, K> result = inverse;
474     return (result == null) ? (inverse = invert()) : result;
475   }
476 
invert()477   private ImmutableSetMultimap<V, K> invert() {
478     Builder<V, K> builder = builder();
479     for (Entry<K, V> entry : entries()) {
480       builder.put(entry.getValue(), entry.getKey());
481     }
482     ImmutableSetMultimap<V, K> invertedMultimap = builder.build();
483     invertedMultimap.inverse = this;
484     return invertedMultimap;
485   }
486 
487   /**
488    * Guaranteed to throw an exception and leave the multimap unmodified.
489    *
490    * @throws UnsupportedOperationException always
491    * @deprecated Unsupported operation.
492    */
493   @CanIgnoreReturnValue
494   @Deprecated
495   @Override
496   @DoNotCall("Always throws UnsupportedOperationException")
removeAll(@heckForNull Object key)497   public final ImmutableSet<V> removeAll(@CheckForNull Object key) {
498     throw new UnsupportedOperationException();
499   }
500 
501   /**
502    * Guaranteed to throw an exception and leave the multimap unmodified.
503    *
504    * @throws UnsupportedOperationException always
505    * @deprecated Unsupported operation.
506    */
507   @CanIgnoreReturnValue
508   @Deprecated
509   @Override
510   @DoNotCall("Always throws UnsupportedOperationException")
replaceValues(K key, Iterable<? extends V> values)511   public final ImmutableSet<V> replaceValues(K key, Iterable<? extends V> values) {
512     throw new UnsupportedOperationException();
513   }
514 
515   @LazyInit @RetainedWith @CheckForNull private transient ImmutableSet<Entry<K, V>> entries;
516 
517   /**
518    * Returns an immutable collection of all key-value pairs in the multimap. Its iterator traverses
519    * the values for the first key, the values for the second key, and so on.
520    */
521   @Override
entries()522   public ImmutableSet<Entry<K, V>> entries() {
523     ImmutableSet<Entry<K, V>> result = entries;
524     return result == null ? (entries = new EntrySet<>(this)) : result;
525   }
526 
527   private static final class EntrySet<K, V> extends ImmutableSet<Entry<K, V>> {
528     @Weak private final transient ImmutableSetMultimap<K, V> multimap;
529 
EntrySet(ImmutableSetMultimap<K, V> multimap)530     EntrySet(ImmutableSetMultimap<K, V> multimap) {
531       this.multimap = multimap;
532     }
533 
534     @Override
contains(@heckForNull Object object)535     public boolean contains(@CheckForNull Object object) {
536       if (object instanceof Entry) {
537         Entry<?, ?> entry = (Entry<?, ?>) object;
538         return multimap.containsEntry(entry.getKey(), entry.getValue());
539       }
540       return false;
541     }
542 
543     @Override
size()544     public int size() {
545       return multimap.size();
546     }
547 
548     @Override
iterator()549     public UnmodifiableIterator<Entry<K, V>> iterator() {
550       return multimap.entryIterator();
551     }
552 
553     @Override
isPartialView()554     boolean isPartialView() {
555       return false;
556     }
557   }
558 
valueSet( @heckForNull Comparator<? super V> valueComparator, Collection<? extends V> values)559   private static <V> ImmutableSet<V> valueSet(
560       @CheckForNull Comparator<? super V> valueComparator, Collection<? extends V> values) {
561     return (valueComparator == null)
562         ? ImmutableSet.copyOf(values)
563         : ImmutableSortedSet.copyOf(valueComparator, values);
564   }
565 
emptySet(@heckForNull Comparator<? super V> valueComparator)566   private static <V> ImmutableSet<V> emptySet(@CheckForNull Comparator<? super V> valueComparator) {
567     return (valueComparator == null)
568         ? ImmutableSet.<V>of()
569         : ImmutableSortedSet.<V>emptySet(valueComparator);
570   }
571 
valuesBuilder( @heckForNull Comparator<? super V> valueComparator)572   private static <V> ImmutableSet.Builder<V> valuesBuilder(
573       @CheckForNull Comparator<? super V> valueComparator) {
574     return (valueComparator == null)
575         ? new ImmutableSet.Builder<V>()
576         : new ImmutableSortedSet.Builder<V>(valueComparator);
577   }
578 
579   /**
580    * @serialData number of distinct keys, and then for each distinct key: the key, the number of
581    *     values for that key, and the key's values
582    */
583   @GwtIncompatible // java.io.ObjectOutputStream
writeObject(ObjectOutputStream stream)584   private void writeObject(ObjectOutputStream stream) throws IOException {
585     stream.defaultWriteObject();
586     stream.writeObject(valueComparator());
587     Serialization.writeMultimap(this, stream);
588   }
589 
590   @CheckForNull
valueComparator()591   Comparator<? super V> valueComparator() {
592     return emptySet instanceof ImmutableSortedSet
593         ? ((ImmutableSortedSet<V>) emptySet).comparator()
594         : null;
595   }
596 
597   @GwtIncompatible // java serialization
598   private static final class SetFieldSettersHolder {
599     static final Serialization.FieldSetter<ImmutableSetMultimap> EMPTY_SET_FIELD_SETTER =
600         Serialization.getFieldSetter(ImmutableSetMultimap.class, "emptySet");
601   }
602 
603   @GwtIncompatible // java.io.ObjectInputStream
604   // Serialization type safety is at the caller's mercy.
605   @SuppressWarnings("unchecked")
readObject(ObjectInputStream stream)606   private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
607     stream.defaultReadObject();
608     Comparator<Object> valueComparator = (Comparator<Object>) stream.readObject();
609     int keyCount = stream.readInt();
610     if (keyCount < 0) {
611       throw new InvalidObjectException("Invalid key count " + keyCount);
612     }
613     ImmutableMap.Builder<Object, ImmutableSet<Object>> builder = ImmutableMap.builder();
614     int tmpSize = 0;
615 
616     for (int i = 0; i < keyCount; i++) {
617       Object key = stream.readObject();
618       int valueCount = stream.readInt();
619       if (valueCount <= 0) {
620         throw new InvalidObjectException("Invalid value count " + valueCount);
621       }
622 
623       ImmutableSet.Builder<Object> valuesBuilder = valuesBuilder(valueComparator);
624       for (int j = 0; j < valueCount; j++) {
625         valuesBuilder.add(stream.readObject());
626       }
627       ImmutableSet<Object> valueSet = valuesBuilder.build();
628       if (valueSet.size() != valueCount) {
629         throw new InvalidObjectException("Duplicate key-value pairs exist for key " + key);
630       }
631       builder.put(key, valueSet);
632       tmpSize += valueCount;
633     }
634 
635     ImmutableMap<Object, ImmutableSet<Object>> tmpMap;
636     try {
637       tmpMap = builder.buildOrThrow();
638     } catch (IllegalArgumentException e) {
639       throw (InvalidObjectException) new InvalidObjectException(e.getMessage()).initCause(e);
640     }
641 
642     FieldSettersHolder.MAP_FIELD_SETTER.set(this, tmpMap);
643     FieldSettersHolder.SIZE_FIELD_SETTER.set(this, tmpSize);
644     SetFieldSettersHolder.EMPTY_SET_FIELD_SETTER.set(this, emptySet(valueComparator));
645   }
646 
647   @GwtIncompatible // not needed in emulated source.
648   private static final long serialVersionUID = 0;
649 }
650