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