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.errorprone.annotations.CanIgnoreReturnValue;
026import com.google.errorprone.annotations.concurrent.LazyInit;
027import com.google.j2objc.annotations.RetainedWith;
028import com.google.j2objc.annotations.Weak;
029import java.io.IOException;
030import java.io.InvalidObjectException;
031import java.io.ObjectInputStream;
032import java.io.ObjectOutputStream;
033import java.util.Arrays;
034import java.util.Collection;
035import java.util.Comparator;
036import java.util.Map;
037import java.util.Map.Entry;
038import org.checkerframework.checker.nullness.compatqual.NullableDecl;
039
040/**
041 * A {@link SetMultimap} whose contents will never change, with many other important properties
042 * detailed at {@link ImmutableCollection}.
043 *
044 * <p>See the Guava User Guide article on <a href=
045 * "https://github.com/google/guava/wiki/ImmutableCollectionsExplained"> immutable collections</a>.
046 *
047 * @author Mike Ward
048 * @since 2.0
049 */
050@GwtCompatible(serializable = true, emulated = true)
051public class ImmutableSetMultimap<K, V> extends ImmutableMultimap<K, V>
052    implements SetMultimap<K, V> {
053
054  /** Returns the empty multimap. */
055  // Casting is safe because the multimap will never hold any elements.
056  @SuppressWarnings("unchecked")
057  public static <K, V> ImmutableSetMultimap<K, V> of() {
058    return (ImmutableSetMultimap<K, V>) EmptyImmutableSetMultimap.INSTANCE;
059  }
060
061  /** Returns an immutable multimap containing a single entry. */
062  public static <K, V> ImmutableSetMultimap<K, V> of(K k1, V v1) {
063    ImmutableSetMultimap.Builder<K, V> builder = ImmutableSetMultimap.builder();
064    builder.put(k1, v1);
065    return builder.build();
066  }
067
068  /**
069   * Returns an immutable multimap containing the given entries, in order. Repeated occurrences of
070   * an entry (according to {@link Object#equals}) after the first are ignored.
071   */
072  public static <K, V> ImmutableSetMultimap<K, V> of(K k1, V v1, K k2, V v2) {
073    ImmutableSetMultimap.Builder<K, V> builder = ImmutableSetMultimap.builder();
074    builder.put(k1, v1);
075    builder.put(k2, v2);
076    return builder.build();
077  }
078
079  /**
080   * Returns an immutable multimap containing the given entries, in order. Repeated occurrences of
081   * an entry (according to {@link Object#equals}) after the first are ignored.
082   */
083  public static <K, V> ImmutableSetMultimap<K, V> of(K k1, V v1, K k2, V v2, K k3, V v3) {
084    ImmutableSetMultimap.Builder<K, V> builder = ImmutableSetMultimap.builder();
085    builder.put(k1, v1);
086    builder.put(k2, v2);
087    builder.put(k3, v3);
088    return builder.build();
089  }
090
091  /**
092   * Returns an immutable multimap containing the given entries, in order. Repeated occurrences of
093   * an entry (according to {@link Object#equals}) after the first are ignored.
094   */
095  public static <K, V> ImmutableSetMultimap<K, V> of(
096      K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4) {
097    ImmutableSetMultimap.Builder<K, V> builder = ImmutableSetMultimap.builder();
098    builder.put(k1, v1);
099    builder.put(k2, v2);
100    builder.put(k3, v3);
101    builder.put(k4, v4);
102    return builder.build();
103  }
104
105  /**
106   * Returns an immutable multimap containing the given entries, in order. Repeated occurrences of
107   * an entry (according to {@link Object#equals}) after the first are ignored.
108   */
109  public static <K, V> ImmutableSetMultimap<K, V> of(
110      K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5) {
111    ImmutableSetMultimap.Builder<K, V> builder = ImmutableSetMultimap.builder();
112    builder.put(k1, v1);
113    builder.put(k2, v2);
114    builder.put(k3, v3);
115    builder.put(k4, v4);
116    builder.put(k5, v5);
117    return builder.build();
118  }
119
120  // looking for of() with > 5 entries? Use the builder instead.
121
122  /** Returns a new {@link Builder}. */
123  public static <K, V> Builder<K, V> builder() {
124    return new Builder<>();
125  }
126
127  /**
128   * A builder for creating immutable {@code SetMultimap} instances, especially {@code public static
129   * final} multimaps ("constant multimaps"). Example:
130   *
131   * <pre>{@code
132   * static final Multimap<String, Integer> STRING_TO_INTEGER_MULTIMAP =
133   *     new ImmutableSetMultimap.Builder<String, Integer>()
134   *         .put("one", 1)
135   *         .putAll("several", 1, 2, 3)
136   *         .putAll("many", 1, 2, 3, 4, 5)
137   *         .build();
138   * }</pre>
139   *
140   * <p>Builder instances can be reused; it is safe to call {@link #build} multiple times to build
141   * multiple multimaps in series. Each multimap contains the key-value mappings in the previously
142   * created multimaps.
143   *
144   * @since 2.0
145   */
146  public static final class Builder<K, V> extends ImmutableMultimap.Builder<K, V> {
147    /**
148     * Creates a new builder. The returned builder is equivalent to the builder generated by {@link
149     * ImmutableSetMultimap#builder}.
150     */
151    public Builder() {
152      super();
153    }
154
155    @Override
156    Collection<V> newMutableValueCollection() {
157      return Platform.preservesInsertionOrderOnAddsSet();
158    }
159
160    /** Adds a key-value mapping to the built multimap if it is not already present. */
161    @CanIgnoreReturnValue
162    @Override
163    public Builder<K, V> put(K key, V value) {
164      super.put(key, value);
165      return this;
166    }
167
168    /**
169     * Adds an entry to the built multimap if it is not already present.
170     *
171     * @since 11.0
172     */
173    @CanIgnoreReturnValue
174    @Override
175    public Builder<K, V> put(Entry<? extends K, ? extends V> entry) {
176      super.put(entry);
177      return this;
178    }
179
180    /**
181     * {@inheritDoc}
182     *
183     * @since 19.0
184     */
185    @CanIgnoreReturnValue
186    @Beta
187    @Override
188    public Builder<K, V> putAll(Iterable<? extends Entry<? extends K, ? extends V>> entries) {
189      super.putAll(entries);
190      return this;
191    }
192
193    @CanIgnoreReturnValue
194    @Override
195    public Builder<K, V> putAll(K key, Iterable<? extends V> values) {
196      super.putAll(key, values);
197      return this;
198    }
199
200    @CanIgnoreReturnValue
201    @Override
202    public Builder<K, V> putAll(K key, V... values) {
203      return putAll(key, Arrays.asList(values));
204    }
205
206    @CanIgnoreReturnValue
207    @Override
208    public Builder<K, V> putAll(Multimap<? extends K, ? extends V> multimap) {
209      for (Entry<? extends K, ? extends Collection<? extends V>> entry :
210          multimap.asMap().entrySet()) {
211        putAll(entry.getKey(), entry.getValue());
212      }
213      return this;
214    }
215
216    /**
217     * {@inheritDoc}
218     *
219     * @since 8.0
220     */
221    @CanIgnoreReturnValue
222    @Override
223    public Builder<K, V> orderKeysBy(Comparator<? super K> keyComparator) {
224      super.orderKeysBy(keyComparator);
225      return this;
226    }
227
228    /**
229     * Specifies the ordering of the generated multimap's values for each key.
230     *
231     * <p>If this method is called, the sets returned by the {@code get()} method of the generated
232     * multimap and its {@link Multimap#asMap()} view are {@link ImmutableSortedSet} instances.
233     * However, serialization does not preserve that property, though it does maintain the key and
234     * value ordering.
235     *
236     * @since 8.0
237     */
238    // TODO: Make serialization behavior consistent.
239    @CanIgnoreReturnValue
240    @Override
241    public Builder<K, V> orderValuesBy(Comparator<? super V> valueComparator) {
242      super.orderValuesBy(valueComparator);
243      return this;
244    }
245
246    /** Returns a newly-created immutable set multimap. */
247    @Override
248    public ImmutableSetMultimap<K, V> build() {
249      Collection<Map.Entry<K, Collection<V>>> mapEntries = builderMap.entrySet();
250      if (keyComparator != null) {
251        mapEntries = Ordering.from(keyComparator).<K>onKeys().immutableSortedCopy(mapEntries);
252      }
253      return fromMapEntries(mapEntries, valueComparator);
254    }
255  }
256
257  /**
258   * Returns an immutable set multimap containing the same mappings as {@code multimap}. The
259   * generated multimap's key and value orderings correspond to the iteration ordering of the {@code
260   * multimap.asMap()} view. Repeated occurrences of an entry in the multimap after the first are
261   * ignored.
262   *
263   * <p>Despite the method name, this method attempts to avoid actually copying the data when it is
264   * safe to do so. The exact circumstances under which a copy will or will not be performed are
265   * undocumented and subject to change.
266   *
267   * @throws NullPointerException if any key or value in {@code multimap} is null
268   */
269  public static <K, V> ImmutableSetMultimap<K, V> copyOf(
270      Multimap<? extends K, ? extends V> multimap) {
271    return copyOf(multimap, null);
272  }
273
274  private static <K, V> ImmutableSetMultimap<K, V> copyOf(
275      Multimap<? extends K, ? extends V> multimap, Comparator<? super V> valueComparator) {
276    checkNotNull(multimap); // eager for GWT
277    if (multimap.isEmpty() && valueComparator == null) {
278      return of();
279    }
280
281    if (multimap instanceof ImmutableSetMultimap) {
282      @SuppressWarnings("unchecked") // safe since multimap is not writable
283      ImmutableSetMultimap<K, V> kvMultimap = (ImmutableSetMultimap<K, V>) multimap;
284      if (!kvMultimap.isPartialView()) {
285        return kvMultimap;
286      }
287    }
288
289    return fromMapEntries(multimap.asMap().entrySet(), valueComparator);
290  }
291
292  /** Creates an ImmutableSetMultimap from an asMap.entrySet. */
293  static <K, V> ImmutableSetMultimap<K, V> fromMapEntries(
294      Collection<? extends Map.Entry<? extends K, ? extends Collection<? extends V>>> mapEntries,
295      @NullableDecl Comparator<? super V> valueComparator) {
296    if (mapEntries.isEmpty()) {
297      return of();
298    }
299    ImmutableMap.Builder<K, ImmutableSet<V>> builder =
300        new ImmutableMap.Builder<>(mapEntries.size());
301    int size = 0;
302
303    for (Entry<? extends K, ? extends Collection<? extends V>> entry : mapEntries) {
304      K key = entry.getKey();
305      Collection<? extends V> values = entry.getValue();
306      ImmutableSet<V> set = valueSet(valueComparator, values);
307      if (!set.isEmpty()) {
308        builder.put(key, set);
309        size += set.size();
310      }
311    }
312
313    return new ImmutableSetMultimap<>(builder.build(), size, valueComparator);
314  }
315
316  /**
317   * Returns an immutable multimap containing the specified entries. The returned multimap iterates
318   * over keys in the order they were first encountered in the input, and the values for each key
319   * are iterated in the order they were encountered. If two values for the same key are {@linkplain
320   * Object#equals equal}, the first value encountered is used.
321   *
322   * @throws NullPointerException if any key, value, or entry is null
323   * @since 19.0
324   */
325  @Beta
326  public static <K, V> ImmutableSetMultimap<K, V> copyOf(
327      Iterable<? extends Entry<? extends K, ? extends V>> entries) {
328    return new Builder<K, V>().putAll(entries).build();
329  }
330
331  /**
332   * Returned by get() when a missing key is provided. Also holds the comparator, if any, used for
333   * values.
334   */
335  private final transient ImmutableSet<V> emptySet;
336
337  ImmutableSetMultimap(
338      ImmutableMap<K, ImmutableSet<V>> map,
339      int size,
340      @NullableDecl Comparator<? super V> valueComparator) {
341    super(map, size);
342    this.emptySet = emptySet(valueComparator);
343  }
344
345  // views
346
347  /**
348   * Returns an immutable set of the values for the given key. If no mappings in the multimap have
349   * the provided key, an empty immutable set is returned. The values are in the same order as the
350   * parameters used to build this multimap.
351   */
352  @Override
353  public ImmutableSet<V> get(@NullableDecl K key) {
354    // This cast is safe as its type is known in constructor.
355    ImmutableSet<V> set = (ImmutableSet<V>) map.get(key);
356    return MoreObjects.firstNonNull(set, emptySet);
357  }
358
359  @LazyInit @RetainedWith private transient ImmutableSetMultimap<V, K> inverse;
360
361  /**
362   * {@inheritDoc}
363   *
364   * <p>Because an inverse of a set multimap cannot contain multiple pairs with the same key and
365   * value, this method returns an {@code ImmutableSetMultimap} rather than the {@code
366   * ImmutableMultimap} specified in the {@code ImmutableMultimap} class.
367   *
368   * @since 11.0
369   */
370  public ImmutableSetMultimap<V, K> inverse() {
371    ImmutableSetMultimap<V, K> result = inverse;
372    return (result == null) ? (inverse = invert()) : result;
373  }
374
375  private ImmutableSetMultimap<V, K> invert() {
376    Builder<V, K> builder = builder();
377    for (Entry<K, V> entry : entries()) {
378      builder.put(entry.getValue(), entry.getKey());
379    }
380    ImmutableSetMultimap<V, K> invertedMultimap = builder.build();
381    invertedMultimap.inverse = this;
382    return invertedMultimap;
383  }
384
385  /**
386   * Guaranteed to throw an exception and leave the multimap unmodified.
387   *
388   * @throws UnsupportedOperationException always
389   * @deprecated Unsupported operation.
390   */
391  @CanIgnoreReturnValue
392  @Deprecated
393  @Override
394  public ImmutableSet<V> removeAll(Object key) {
395    throw new UnsupportedOperationException();
396  }
397
398  /**
399   * Guaranteed to throw an exception and leave the multimap unmodified.
400   *
401   * @throws UnsupportedOperationException always
402   * @deprecated Unsupported operation.
403   */
404  @CanIgnoreReturnValue
405  @Deprecated
406  @Override
407  public ImmutableSet<V> replaceValues(K key, Iterable<? extends V> values) {
408    throw new UnsupportedOperationException();
409  }
410
411  private transient ImmutableSet<Entry<K, V>> entries;
412
413  /**
414   * Returns an immutable collection of all key-value pairs in the multimap. Its iterator traverses
415   * the values for the first key, the values for the second key, and so on.
416   */
417  @Override
418  public ImmutableSet<Entry<K, V>> entries() {
419    ImmutableSet<Entry<K, V>> result = entries;
420    return result == null ? (entries = new EntrySet<>(this)) : result;
421  }
422
423  private static final class EntrySet<K, V> extends ImmutableSet<Entry<K, V>> {
424    @Weak private final transient ImmutableSetMultimap<K, V> multimap;
425
426    EntrySet(ImmutableSetMultimap<K, V> multimap) {
427      this.multimap = multimap;
428    }
429
430    @Override
431    public boolean contains(@NullableDecl Object object) {
432      if (object instanceof Entry) {
433        Entry<?, ?> entry = (Entry<?, ?>) object;
434        return multimap.containsEntry(entry.getKey(), entry.getValue());
435      }
436      return false;
437    }
438
439    @Override
440    public int size() {
441      return multimap.size();
442    }
443
444    @Override
445    public UnmodifiableIterator<Entry<K, V>> iterator() {
446      return multimap.entryIterator();
447    }
448
449    @Override
450    boolean isPartialView() {
451      return false;
452    }
453  }
454
455  private static <V> ImmutableSet<V> valueSet(
456      @NullableDecl Comparator<? super V> valueComparator, Collection<? extends V> values) {
457    return (valueComparator == null)
458        ? ImmutableSet.copyOf(values)
459        : ImmutableSortedSet.copyOf(valueComparator, values);
460  }
461
462  private static <V> ImmutableSet<V> emptySet(@NullableDecl Comparator<? super V> valueComparator) {
463    return (valueComparator == null)
464        ? ImmutableSet.<V>of()
465        : ImmutableSortedSet.<V>emptySet(valueComparator);
466  }
467
468  private static <V> ImmutableSet.Builder<V> valuesBuilder(
469      @NullableDecl Comparator<? super V> valueComparator) {
470    return (valueComparator == null)
471        ? new ImmutableSet.Builder<V>()
472        : new ImmutableSortedSet.Builder<V>(valueComparator);
473  }
474
475  /**
476   * @serialData number of distinct keys, and then for each distinct key: the key, the number of
477   *     values for that key, and the key's values
478   */
479  @GwtIncompatible // java.io.ObjectOutputStream
480  private void writeObject(ObjectOutputStream stream) throws IOException {
481    stream.defaultWriteObject();
482    stream.writeObject(valueComparator());
483    Serialization.writeMultimap(this, stream);
484  }
485
486  @NullableDecl
487  Comparator<? super V> valueComparator() {
488    return emptySet instanceof ImmutableSortedSet
489        ? ((ImmutableSortedSet<V>) emptySet).comparator()
490        : null;
491  }
492  
493  @GwtIncompatible // java serialization
494  private static final class SetFieldSettersHolder {
495    static final Serialization.FieldSetter<ImmutableSetMultimap> EMPTY_SET_FIELD_SETTER =
496        Serialization.getFieldSetter(ImmutableSetMultimap.class, "emptySet");
497  }
498
499  @GwtIncompatible // java.io.ObjectInputStream
500  // Serialization type safety is at the caller's mercy.
501  @SuppressWarnings("unchecked")
502  private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
503    stream.defaultReadObject();
504    Comparator<Object> valueComparator = (Comparator<Object>) stream.readObject();
505    int keyCount = stream.readInt();
506    if (keyCount < 0) {
507      throw new InvalidObjectException("Invalid key count " + keyCount);
508    }
509    ImmutableMap.Builder<Object, ImmutableSet<Object>> builder = ImmutableMap.builder();
510    int tmpSize = 0;
511
512    for (int i = 0; i < keyCount; i++) {
513      Object key = stream.readObject();
514      int valueCount = stream.readInt();
515      if (valueCount <= 0) {
516        throw new InvalidObjectException("Invalid value count " + valueCount);
517      }
518
519      ImmutableSet.Builder<Object> valuesBuilder = valuesBuilder(valueComparator);
520      for (int j = 0; j < valueCount; j++) {
521        valuesBuilder.add(stream.readObject());
522      }
523      ImmutableSet<Object> valueSet = valuesBuilder.build();
524      if (valueSet.size() != valueCount) {
525        throw new InvalidObjectException("Duplicate key-value pairs exist for key " + key);
526      }
527      builder.put(key, valueSet);
528      tmpSize += valueCount;
529    }
530
531    ImmutableMap<Object, ImmutableSet<Object>> tmpMap;
532    try {
533      tmpMap = builder.build();
534    } catch (IllegalArgumentException e) {
535      throw (InvalidObjectException) new InvalidObjectException(e.getMessage()).initCause(e);
536    }
537
538    FieldSettersHolder.MAP_FIELD_SETTER.set(this, tmpMap);
539    FieldSettersHolder.SIZE_FIELD_SETTER.set(this, tmpSize);
540    SetFieldSettersHolder.EMPTY_SET_FIELD_SETTER.set(this, emptySet(valueComparator));
541  }
542
543  @GwtIncompatible // not needed in emulated source.
544  private static final long serialVersionUID = 0;
545}