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