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