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