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  /**
293   * Returns an immutable multimap containing the specified entries. The returned multimap iterates
294   * over keys in the order they were first encountered in the input, and the values for each key
295   * are iterated in the order they were encountered. If two values for the same key are {@linkplain
296   * Object#equals equal}, the first value encountered is used.
297   *
298   * @throws NullPointerException if any key, value, or entry is null
299   * @since 19.0
300   */
301  @Beta
302  public static <K, V> ImmutableSetMultimap<K, V> copyOf(
303      Iterable<? extends Entry<? extends K, ? extends V>> entries) {
304    return new Builder<K, V>().putAll(entries).build();
305  }
306
307  /** Creates an ImmutableSetMultimap from an asMap.entrySet. */
308  static <K, V> ImmutableSetMultimap<K, V> fromMapEntries(
309      Collection<? extends Map.Entry<? extends K, ? extends Collection<? extends V>>> mapEntries,
310      @NullableDecl Comparator<? super V> valueComparator) {
311    if (mapEntries.isEmpty()) {
312      return of();
313    }
314    ImmutableMap.Builder<K, ImmutableSet<V>> builder =
315        new ImmutableMap.Builder<>(mapEntries.size());
316    int size = 0;
317
318    for (Entry<? extends K, ? extends Collection<? extends V>> entry : mapEntries) {
319      K key = entry.getKey();
320      Collection<? extends V> values = entry.getValue();
321      ImmutableSet<V> set = valueSet(valueComparator, values);
322      if (!set.isEmpty()) {
323        builder.put(key, set);
324        size += set.size();
325      }
326    }
327
328    return new ImmutableSetMultimap<>(builder.build(), size, valueComparator);
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 @NullableDecl 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  @Override
369  public ImmutableSetMultimap<V, K> inverse() {
370    ImmutableSetMultimap<V, K> result = inverse;
371    return (result == null) ? (inverse = invert()) : result;
372  }
373
374  private ImmutableSetMultimap<V, K> invert() {
375    Builder<V, K> builder = builder();
376    for (Entry<K, V> entry : entries()) {
377      builder.put(entry.getValue(), entry.getKey());
378    }
379    ImmutableSetMultimap<V, K> invertedMultimap = builder.build();
380    invertedMultimap.inverse = this;
381    return invertedMultimap;
382  }
383
384  /**
385   * Guaranteed to throw an exception and leave the multimap unmodified.
386   *
387   * @throws UnsupportedOperationException always
388   * @deprecated Unsupported operation.
389   */
390  @CanIgnoreReturnValue
391  @Deprecated
392  @Override
393  public ImmutableSet<V> removeAll(Object key) {
394    throw new UnsupportedOperationException();
395  }
396
397  /**
398   * Guaranteed to throw an exception and leave the multimap unmodified.
399   *
400   * @throws UnsupportedOperationException always
401   * @deprecated Unsupported operation.
402   */
403  @CanIgnoreReturnValue
404  @Deprecated
405  @Override
406  public ImmutableSet<V> replaceValues(K key, Iterable<? extends V> values) {
407    throw new UnsupportedOperationException();
408  }
409
410  @LazyInit @RetainedWith @NullableDecl private transient ImmutableSet<Entry<K, V>> entries;
411
412  /**
413   * Returns an immutable collection of all key-value pairs in the multimap. Its iterator traverses
414   * the values for the first key, the values for the second key, and so on.
415   */
416  @Override
417  public ImmutableSet<Entry<K, V>> entries() {
418    ImmutableSet<Entry<K, V>> result = entries;
419    return result == null ? (entries = new EntrySet<>(this)) : result;
420  }
421
422  private static final class EntrySet<K, V> extends ImmutableSet<Entry<K, V>> {
423    @Weak private final transient ImmutableSetMultimap<K, V> multimap;
424
425    EntrySet(ImmutableSetMultimap<K, V> multimap) {
426      this.multimap = multimap;
427    }
428
429    @Override
430    public boolean contains(@NullableDecl Object object) {
431      if (object instanceof Entry) {
432        Entry<?, ?> entry = (Entry<?, ?>) object;
433        return multimap.containsEntry(entry.getKey(), entry.getValue());
434      }
435      return false;
436    }
437
438    @Override
439    public int size() {
440      return multimap.size();
441    }
442
443    @Override
444    public UnmodifiableIterator<Entry<K, V>> iterator() {
445      return multimap.entryIterator();
446    }
447
448    @Override
449    boolean isPartialView() {
450      return false;
451    }
452  }
453
454  private static <V> ImmutableSet<V> valueSet(
455      @NullableDecl Comparator<? super V> valueComparator, Collection<? extends V> values) {
456    return (valueComparator == null)
457        ? ImmutableSet.copyOf(values)
458        : ImmutableSortedSet.copyOf(valueComparator, values);
459  }
460
461  private static <V> ImmutableSet<V> emptySet(@NullableDecl Comparator<? super V> valueComparator) {
462    return (valueComparator == null)
463        ? ImmutableSet.<V>of()
464        : ImmutableSortedSet.<V>emptySet(valueComparator);
465  }
466
467  private static <V> ImmutableSet.Builder<V> valuesBuilder(
468      @NullableDecl Comparator<? super V> valueComparator) {
469    return (valueComparator == null)
470        ? new ImmutableSet.Builder<V>()
471        : new ImmutableSortedSet.Builder<V>(valueComparator);
472  }
473
474  /**
475   * @serialData number of distinct keys, and then for each distinct key: the key, the number of
476   *     values for that key, and the key's values
477   */
478  @GwtIncompatible // java.io.ObjectOutputStream
479  private void writeObject(ObjectOutputStream stream) throws IOException {
480    stream.defaultWriteObject();
481    stream.writeObject(valueComparator());
482    Serialization.writeMultimap(this, stream);
483  }
484
485  @NullableDecl
486  Comparator<? super V> valueComparator() {
487    return emptySet instanceof ImmutableSortedSet
488        ? ((ImmutableSortedSet<V>) emptySet).comparator()
489        : null;
490  }
491
492  @GwtIncompatible // java serialization
493  private static final class SetFieldSettersHolder {
494    static final Serialization.FieldSetter<ImmutableSetMultimap> EMPTY_SET_FIELD_SETTER =
495        Serialization.getFieldSetter(ImmutableSetMultimap.class, "emptySet");
496  }
497
498  @GwtIncompatible // java.io.ObjectInputStream
499  // Serialization type safety is at the caller's mercy.
500  @SuppressWarnings("unchecked")
501  private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
502    stream.defaultReadObject();
503    Comparator<Object> valueComparator = (Comparator<Object>) stream.readObject();
504    int keyCount = stream.readInt();
505    if (keyCount < 0) {
506      throw new InvalidObjectException("Invalid key count " + keyCount);
507    }
508    ImmutableMap.Builder<Object, ImmutableSet<Object>> builder = ImmutableMap.builder();
509    int tmpSize = 0;
510
511    for (int i = 0; i < keyCount; i++) {
512      Object key = stream.readObject();
513      int valueCount = stream.readInt();
514      if (valueCount <= 0) {
515        throw new InvalidObjectException("Invalid value count " + valueCount);
516      }
517
518      ImmutableSet.Builder<Object> valuesBuilder = valuesBuilder(valueComparator);
519      for (int j = 0; j < valueCount; j++) {
520        valuesBuilder.add(stream.readObject());
521      }
522      ImmutableSet<Object> valueSet = valuesBuilder.build();
523      if (valueSet.size() != valueCount) {
524        throw new InvalidObjectException("Duplicate key-value pairs exist for key " + key);
525      }
526      builder.put(key, valueSet);
527      tmpSize += valueCount;
528    }
529
530    ImmutableMap<Object, ImmutableSet<Object>> tmpMap;
531    try {
532      tmpMap = builder.build();
533    } catch (IllegalArgumentException e) {
534      throw (InvalidObjectException) new InvalidObjectException(e.getMessage()).initCause(e);
535    }
536
537    FieldSettersHolder.MAP_FIELD_SETTER.set(this, tmpMap);
538    FieldSettersHolder.SIZE_FIELD_SETTER.set(this, tmpSize);
539    SetFieldSettersHolder.EMPTY_SET_FIELD_SETTER.set(this, emptySet(valueComparator));
540  }
541
542  @GwtIncompatible // not needed in emulated source.
543  private static final long serialVersionUID = 0;
544}