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