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