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.DoNotCall;
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 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    @CanIgnoreReturnValue
218    @Override
219    Builder<K, V> combine(ImmutableMultimap.Builder<K, V> other) {
220      super.combine(other);
221      return this;
222    }
223
224    /**
225     * {@inheritDoc}
226     *
227     * @since 8.0
228     */
229    @CanIgnoreReturnValue
230    @Override
231    public Builder<K, V> orderKeysBy(Comparator<? super K> keyComparator) {
232      super.orderKeysBy(keyComparator);
233      return this;
234    }
235
236    /**
237     * Specifies the ordering of the generated multimap's values for each key.
238     *
239     * <p>If this method is called, the sets returned by the {@code get()} method of the generated
240     * multimap and its {@link Multimap#asMap()} view are {@link ImmutableSortedSet} instances.
241     * However, serialization does not preserve that property, though it does maintain the key and
242     * value ordering.
243     *
244     * @since 8.0
245     */
246    // TODO: Make serialization behavior consistent.
247    @CanIgnoreReturnValue
248    @Override
249    public Builder<K, V> orderValuesBy(Comparator<? super V> valueComparator) {
250      super.orderValuesBy(valueComparator);
251      return this;
252    }
253
254    /** Returns a newly-created immutable set multimap. */
255    @Override
256    public ImmutableSetMultimap<K, V> build() {
257      Collection<Map.Entry<K, Collection<V>>> mapEntries = builderMap.entrySet();
258      if (keyComparator != null) {
259        mapEntries = Ordering.from(keyComparator).<K>onKeys().immutableSortedCopy(mapEntries);
260      }
261      return fromMapEntries(mapEntries, valueComparator);
262    }
263  }
264
265  /**
266   * Returns an immutable set multimap containing the same mappings as {@code multimap}. The
267   * generated multimap's key and value orderings correspond to the iteration ordering of the {@code
268   * multimap.asMap()} view. Repeated occurrences of an entry in the multimap after the first are
269   * ignored.
270   *
271   * <p>Despite the method name, this method attempts to avoid actually copying the data when it is
272   * safe to do so. The exact circumstances under which a copy will or will not be performed are
273   * undocumented and subject to change.
274   *
275   * @throws NullPointerException if any key or value in {@code multimap} is null
276   */
277  public static <K, V> ImmutableSetMultimap<K, V> copyOf(
278      Multimap<? extends K, ? extends V> multimap) {
279    return copyOf(multimap, null);
280  }
281
282  private static <K, V> ImmutableSetMultimap<K, V> copyOf(
283      Multimap<? extends K, ? extends V> multimap, Comparator<? super V> valueComparator) {
284    checkNotNull(multimap); // eager for GWT
285    if (multimap.isEmpty() && valueComparator == null) {
286      return of();
287    }
288
289    if (multimap instanceof ImmutableSetMultimap) {
290      @SuppressWarnings("unchecked") // safe since multimap is not writable
291      ImmutableSetMultimap<K, V> kvMultimap = (ImmutableSetMultimap<K, V>) multimap;
292      if (!kvMultimap.isPartialView()) {
293        return kvMultimap;
294      }
295    }
296
297    return fromMapEntries(multimap.asMap().entrySet(), valueComparator);
298  }
299
300  /**
301   * Returns an immutable multimap containing the specified entries. The returned multimap iterates
302   * over keys in the order they were first encountered in the input, and the values for each key
303   * are iterated in the order they were encountered. If two values for the same key are {@linkplain
304   * Object#equals equal}, the first value encountered is used.
305   *
306   * @throws NullPointerException if any key, value, or entry is null
307   * @since 19.0
308   */
309  @Beta
310  public static <K, V> ImmutableSetMultimap<K, V> copyOf(
311      Iterable<? extends Entry<? extends K, ? extends V>> entries) {
312    return new Builder<K, V>().putAll(entries).build();
313  }
314
315  /** Creates an ImmutableSetMultimap from an asMap.entrySet. */
316  static <K, V> ImmutableSetMultimap<K, V> fromMapEntries(
317      Collection<? extends Map.Entry<? extends K, ? extends Collection<? extends V>>> mapEntries,
318      @NullableDecl Comparator<? super V> valueComparator) {
319    if (mapEntries.isEmpty()) {
320      return of();
321    }
322    ImmutableMap.Builder<K, ImmutableSet<V>> builder =
323        new ImmutableMap.Builder<>(mapEntries.size());
324    int size = 0;
325
326    for (Entry<? extends K, ? extends Collection<? extends V>> entry : mapEntries) {
327      K key = entry.getKey();
328      Collection<? extends V> values = entry.getValue();
329      ImmutableSet<V> set = valueSet(valueComparator, values);
330      if (!set.isEmpty()) {
331        builder.put(key, set);
332        size += set.size();
333      }
334    }
335
336    return new ImmutableSetMultimap<>(builder.build(), size, valueComparator);
337  }
338
339  /**
340   * Returned by get() when a missing key is provided. Also holds the comparator, if any, used for
341   * values.
342   */
343  private final transient ImmutableSet<V> emptySet;
344
345  ImmutableSetMultimap(
346      ImmutableMap<K, ImmutableSet<V>> map,
347      int size,
348      @NullableDecl Comparator<? super V> valueComparator) {
349    super(map, size);
350    this.emptySet = emptySet(valueComparator);
351  }
352
353  // views
354
355  /**
356   * Returns an immutable set of the values for the given key. If no mappings in the multimap have
357   * the provided key, an empty immutable set is returned. The values are in the same order as the
358   * parameters used to build this multimap.
359   */
360  @Override
361  public ImmutableSet<V> get(@NullableDecl K key) {
362    // This cast is safe as its type is known in constructor.
363    ImmutableSet<V> set = (ImmutableSet<V>) map.get(key);
364    return MoreObjects.firstNonNull(set, emptySet);
365  }
366
367  @LazyInit @RetainedWith @NullableDecl private transient ImmutableSetMultimap<V, K> inverse;
368
369  /**
370   * {@inheritDoc}
371   *
372   * <p>Because an inverse of a set multimap cannot contain multiple pairs with the same key and
373   * value, this method returns an {@code ImmutableSetMultimap} rather than the {@code
374   * ImmutableMultimap} specified in the {@code ImmutableMultimap} class.
375   */
376  @Override
377  public ImmutableSetMultimap<V, K> inverse() {
378    ImmutableSetMultimap<V, K> result = inverse;
379    return (result == null) ? (inverse = invert()) : result;
380  }
381
382  private ImmutableSetMultimap<V, K> invert() {
383    Builder<V, K> builder = builder();
384    for (Entry<K, V> entry : entries()) {
385      builder.put(entry.getValue(), entry.getKey());
386    }
387    ImmutableSetMultimap<V, K> invertedMultimap = builder.build();
388    invertedMultimap.inverse = this;
389    return invertedMultimap;
390  }
391
392  /**
393   * Guaranteed to throw an exception and leave the multimap unmodified.
394   *
395   * @throws UnsupportedOperationException always
396   * @deprecated Unsupported operation.
397   */
398  @CanIgnoreReturnValue
399  @Deprecated
400  @Override
401  @DoNotCall("Always throws UnsupportedOperationException")
402  public final ImmutableSet<V> removeAll(Object key) {
403    throw new UnsupportedOperationException();
404  }
405
406  /**
407   * Guaranteed to throw an exception and leave the multimap unmodified.
408   *
409   * @throws UnsupportedOperationException always
410   * @deprecated Unsupported operation.
411   */
412  @CanIgnoreReturnValue
413  @Deprecated
414  @Override
415  @DoNotCall("Always throws UnsupportedOperationException")
416  public final ImmutableSet<V> replaceValues(K key, Iterable<? extends V> values) {
417    throw new UnsupportedOperationException();
418  }
419
420  @LazyInit @RetainedWith @NullableDecl private transient ImmutableSet<Entry<K, V>> entries;
421
422  /**
423   * Returns an immutable collection of all key-value pairs in the multimap. Its iterator traverses
424   * the values for the first key, the values for the second key, and so on.
425   */
426  @Override
427  public ImmutableSet<Entry<K, V>> entries() {
428    ImmutableSet<Entry<K, V>> result = entries;
429    return result == null ? (entries = new EntrySet<>(this)) : result;
430  }
431
432  private static final class EntrySet<K, V> extends ImmutableSet<Entry<K, V>> {
433    @Weak private final transient ImmutableSetMultimap<K, V> multimap;
434
435    EntrySet(ImmutableSetMultimap<K, V> multimap) {
436      this.multimap = multimap;
437    }
438
439    @Override
440    public boolean contains(@NullableDecl Object object) {
441      if (object instanceof Entry) {
442        Entry<?, ?> entry = (Entry<?, ?>) object;
443        return multimap.containsEntry(entry.getKey(), entry.getValue());
444      }
445      return false;
446    }
447
448    @Override
449    public int size() {
450      return multimap.size();
451    }
452
453    @Override
454    public UnmodifiableIterator<Entry<K, V>> iterator() {
455      return multimap.entryIterator();
456    }
457
458    @Override
459    boolean isPartialView() {
460      return false;
461    }
462  }
463
464  private static <V> ImmutableSet<V> valueSet(
465      @NullableDecl Comparator<? super V> valueComparator, Collection<? extends V> values) {
466    return (valueComparator == null)
467        ? ImmutableSet.copyOf(values)
468        : ImmutableSortedSet.copyOf(valueComparator, values);
469  }
470
471  private static <V> ImmutableSet<V> emptySet(@NullableDecl Comparator<? super V> valueComparator) {
472    return (valueComparator == null)
473        ? ImmutableSet.<V>of()
474        : ImmutableSortedSet.<V>emptySet(valueComparator);
475  }
476
477  private static <V> ImmutableSet.Builder<V> valuesBuilder(
478      @NullableDecl Comparator<? super V> valueComparator) {
479    return (valueComparator == null)
480        ? new ImmutableSet.Builder<V>()
481        : new ImmutableSortedSet.Builder<V>(valueComparator);
482  }
483
484  /**
485   * @serialData number of distinct keys, and then for each distinct key: the key, the number of
486   *     values for that key, and the key's values
487   */
488  @GwtIncompatible // java.io.ObjectOutputStream
489  private void writeObject(ObjectOutputStream stream) throws IOException {
490    stream.defaultWriteObject();
491    stream.writeObject(valueComparator());
492    Serialization.writeMultimap(this, stream);
493  }
494
495  @NullableDecl
496  Comparator<? super V> valueComparator() {
497    return emptySet instanceof ImmutableSortedSet
498        ? ((ImmutableSortedSet<V>) emptySet).comparator()
499        : null;
500  }
501
502  @GwtIncompatible // java serialization
503  private static final class SetFieldSettersHolder {
504    static final Serialization.FieldSetter<ImmutableSetMultimap> EMPTY_SET_FIELD_SETTER =
505        Serialization.getFieldSetter(ImmutableSetMultimap.class, "emptySet");
506  }
507
508  @GwtIncompatible // java.io.ObjectInputStream
509  // Serialization type safety is at the caller's mercy.
510  @SuppressWarnings("unchecked")
511  private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
512    stream.defaultReadObject();
513    Comparator<Object> valueComparator = (Comparator<Object>) stream.readObject();
514    int keyCount = stream.readInt();
515    if (keyCount < 0) {
516      throw new InvalidObjectException("Invalid key count " + keyCount);
517    }
518    ImmutableMap.Builder<Object, ImmutableSet<Object>> builder = ImmutableMap.builder();
519    int tmpSize = 0;
520
521    for (int i = 0; i < keyCount; i++) {
522      Object key = stream.readObject();
523      int valueCount = stream.readInt();
524      if (valueCount <= 0) {
525        throw new InvalidObjectException("Invalid value count " + valueCount);
526      }
527
528      ImmutableSet.Builder<Object> valuesBuilder = valuesBuilder(valueComparator);
529      for (int j = 0; j < valueCount; j++) {
530        valuesBuilder.add(stream.readObject());
531      }
532      ImmutableSet<Object> valueSet = valuesBuilder.build();
533      if (valueSet.size() != valueCount) {
534        throw new InvalidObjectException("Duplicate key-value pairs exist for key " + key);
535      }
536      builder.put(key, valueSet);
537      tmpSize += valueCount;
538    }
539
540    ImmutableMap<Object, ImmutableSet<Object>> tmpMap;
541    try {
542      tmpMap = builder.build();
543    } catch (IllegalArgumentException e) {
544      throw (InvalidObjectException) new InvalidObjectException(e.getMessage()).initCause(e);
545    }
546
547    FieldSettersHolder.MAP_FIELD_SETTER.set(this, tmpMap);
548    FieldSettersHolder.SIZE_FIELD_SETTER.set(this, tmpSize);
549    SetFieldSettersHolder.EMPTY_SET_FIELD_SETTER.set(this, emptySet(valueComparator));
550  }
551
552  @GwtIncompatible // not needed in emulated source.
553  private static final long serialVersionUID = 0;
554}