001/*
002 * Copyright (C) 2008 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.collect.CollectPreconditions.checkNonnegative;
020import static java.util.Objects.requireNonNull;
021
022import com.google.common.annotations.GwtCompatible;
023import com.google.common.annotations.GwtIncompatible;
024import com.google.common.annotations.J2ktIncompatible;
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 java.io.IOException;
030import java.io.InvalidObjectException;
031import java.io.ObjectInputStream;
032import java.io.ObjectOutputStream;
033import java.util.Collection;
034import java.util.Comparator;
035import java.util.Map;
036import java.util.Map.Entry;
037import java.util.function.Function;
038import java.util.stream.Collector;
039import java.util.stream.Stream;
040import org.jspecify.annotations.Nullable;
041
042/**
043 * A {@link ListMultimap} whose contents will never change, with many other important properties
044 * detailed at {@link ImmutableCollection}.
045 *
046 * <p>See the Guava User Guide article on <a href=
047 * "https://github.com/google/guava/wiki/ImmutableCollectionsExplained">immutable collections</a>.
048 *
049 * @author Jared Levy
050 * @since 2.0
051 */
052@SuppressWarnings("TooManyParameters")
053@GwtCompatible
054public class ImmutableListMultimap<K, V> extends ImmutableMultimap<K, V>
055    implements ListMultimap<K, V> {
056  /**
057   * Returns a {@link Collector} that accumulates elements into an {@code ImmutableListMultimap}
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   * {@snippet :
068   * static final Multimap<Character, String> FIRST_LETTER_MULTIMAP =
069   *     Stream.of("banana", "apple", "carrot", "asparagus", "cherry")
070   *         .collect(toImmutableListMultimap(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 ImmutableListMultimap.Builder<Character, String>()
076   *         .put('b', "anana")
077   *         .putAll('a', "pple", "sparagus")
078   *         .putAll('c', "arrot", "herry")
079   *         .build();
080   * }
081   *
082   * @since 21.0
083   */
084  public static <T extends @Nullable Object, K, V>
085      Collector<T, ?, ImmutableListMultimap<K, V>> toImmutableListMultimap(
086          Function<? super T, ? extends K> keyFunction,
087          Function<? super T, ? extends V> valueFunction) {
088    return CollectCollectors.toImmutableListMultimap(keyFunction, valueFunction);
089  }
090
091  /**
092   * Returns a {@code Collector} accumulating entries into an {@code ImmutableListMultimap}. 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   * {@snippet :
100   * static final ImmutableListMultimap<Character, Character> FIRST_LETTER_MULTIMAP =
101   *     Stream.of("banana", "apple", "carrot", "asparagus", "cherry")
102   *         .collect(
103   *             flatteningToImmutableListMultimap(
104   *                  str -> str.charAt(0),
105   *                  str -> str.substring(1).chars().mapToObj(c -> (char) c));
106   *
107   * // is equivalent to
108   *
109   * static final ImmutableListMultimap<Character, Character> FIRST_LETTER_MULTIMAP =
110   *     ImmutableListMultimap.<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   *
119   * }
120   *
121   * @since 21.0
122   */
123  public static <T extends @Nullable Object, K, V>
124      Collector<T, ?, ImmutableListMultimap<K, V>> flatteningToImmutableListMultimap(
125          Function<? super T, ? extends K> keyFunction,
126          Function<? super T, ? extends Stream<? extends V>> valuesFunction) {
127    return CollectCollectors.flatteningToImmutableListMultimap(keyFunction, valuesFunction);
128  }
129
130  /**
131   * Returns the empty multimap.
132   *
133   * <p><b>Performance note:</b> the instance returned is a singleton.
134   */
135  // Casting is safe because the multimap will never hold any elements.
136  @SuppressWarnings("unchecked")
137  public static <K, V> ImmutableListMultimap<K, V> of() {
138    return (ImmutableListMultimap<K, V>) EmptyImmutableListMultimap.INSTANCE;
139  }
140
141  /** Returns an immutable multimap containing a single entry. */
142  public static <K, V> ImmutableListMultimap<K, V> of(K k1, V v1) {
143    ImmutableListMultimap.Builder<K, V> builder = builder();
144    builder.put(k1, v1);
145    return builder.build();
146  }
147
148  /** Returns an immutable multimap containing the given entries, in order. */
149  public static <K, V> ImmutableListMultimap<K, V> of(K k1, V v1, K k2, V v2) {
150    ImmutableListMultimap.Builder<K, V> builder = builder();
151    builder.put(k1, v1);
152    builder.put(k2, v2);
153    return builder.build();
154  }
155
156  /** Returns an immutable multimap containing the given entries, in order. */
157  public static <K, V> ImmutableListMultimap<K, V> of(K k1, V v1, K k2, V v2, K k3, V v3) {
158    ImmutableListMultimap.Builder<K, V> builder = builder();
159    builder.put(k1, v1);
160    builder.put(k2, v2);
161    builder.put(k3, v3);
162    return builder.build();
163  }
164
165  /** Returns an immutable multimap containing the given entries, in order. */
166  public static <K, V> ImmutableListMultimap<K, V> of(
167      K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4) {
168    ImmutableListMultimap.Builder<K, V> builder = builder();
169    builder.put(k1, v1);
170    builder.put(k2, v2);
171    builder.put(k3, v3);
172    builder.put(k4, v4);
173    return builder.build();
174  }
175
176  /** Returns an immutable multimap containing the given entries, in order. */
177  public static <K, V> ImmutableListMultimap<K, V> of(
178      K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5) {
179    ImmutableListMultimap.Builder<K, V> builder = builder();
180    builder.put(k1, v1);
181    builder.put(k2, v2);
182    builder.put(k3, v3);
183    builder.put(k4, v4);
184    builder.put(k5, v5);
185    return builder.build();
186  }
187
188  // looking for of() with > 5 entries? Use the builder instead.
189
190  /**
191   * Returns a new builder. The generated builder is equivalent to the builder created by the {@link
192   * Builder} constructor.
193   */
194  public static <K, V> Builder<K, V> builder() {
195    return new Builder<>();
196  }
197
198  /**
199   * Returns a new builder with a hint for how many distinct keys are expected to be added. The
200   * generated builder is equivalent to that returned by {@link #builder}, but may perform better if
201   * {@code expectedKeys} is a good estimate.
202   *
203   * @throws IllegalArgumentException if {@code expectedKeys} is negative
204   * @since 33.3.0
205   */
206  public static <K, V> Builder<K, V> builderWithExpectedKeys(int expectedKeys) {
207    checkNonnegative(expectedKeys, "expectedKeys");
208    return new Builder<>(expectedKeys);
209  }
210
211  /**
212   * A builder for creating immutable {@code ListMultimap} instances, especially {@code public
213   * static final} multimaps ("constant multimaps"). Example:
214   *
215   * {@snippet :
216   * static final Multimap<String, Integer> STRING_TO_INTEGER_MULTIMAP =
217   *     new ImmutableListMultimap.Builder<String, Integer>()
218   *         .put("one", 1)
219   *         .putAll("several", 1, 2, 3)
220   *         .putAll("many", 1, 2, 3, 4, 5)
221   *         .build();
222   * }
223   *
224   * <p>Builder instances can be reused; it is safe to call {@link #build} multiple times to build
225   * multiple multimaps in series. Each multimap contains the key-value mappings in the previously
226   * created multimaps.
227   *
228   * @since 2.0
229   */
230  public static final class Builder<K, V> extends ImmutableMultimap.Builder<K, V> {
231    /**
232     * Creates a new builder. The returned builder is equivalent to the builder generated by {@link
233     * ImmutableListMultimap#builder}.
234     */
235    public Builder() {}
236
237    /** Creates a new builder with a hint for the number of distinct keys. */
238    Builder(int expectedKeys) {
239      super(expectedKeys);
240    }
241
242    /**
243     * {@inheritDoc}
244     *
245     * @since 33.3.0
246     */
247    @CanIgnoreReturnValue
248    @Override
249    public Builder<K, V> expectedValuesPerKey(int expectedValuesPerKey) {
250      super.expectedValuesPerKey(expectedValuesPerKey);
251      return this;
252    }
253
254    @CanIgnoreReturnValue
255    @Override
256    public Builder<K, V> put(K key, V value) {
257      super.put(key, value);
258      return this;
259    }
260
261    /**
262     * {@inheritDoc}
263     *
264     * @since 11.0
265     */
266    @CanIgnoreReturnValue
267    @Override
268    public Builder<K, V> put(Entry<? extends K, ? extends V> entry) {
269      super.put(entry);
270      return this;
271    }
272
273    /**
274     * {@inheritDoc}
275     *
276     * @since 19.0
277     */
278    @CanIgnoreReturnValue
279    @Override
280    public Builder<K, V> putAll(Iterable<? extends Entry<? extends K, ? extends V>> entries) {
281      super.putAll(entries);
282      return this;
283    }
284
285    @CanIgnoreReturnValue
286    @Override
287    public Builder<K, V> putAll(K key, Iterable<? extends V> values) {
288      super.putAll(key, values);
289      return this;
290    }
291
292    @CanIgnoreReturnValue
293    @Override
294    public Builder<K, V> putAll(K key, V... values) {
295      super.putAll(key, values);
296      return this;
297    }
298
299    @CanIgnoreReturnValue
300    @Override
301    public Builder<K, V> putAll(Multimap<? extends K, ? extends V> multimap) {
302      super.putAll(multimap);
303      return this;
304    }
305
306    @CanIgnoreReturnValue
307    @Override
308    Builder<K, V> combine(ImmutableMultimap.Builder<K, V> other) {
309      super.combine(other);
310      return this;
311    }
312
313    /**
314     * {@inheritDoc}
315     *
316     * @since 8.0
317     */
318    @CanIgnoreReturnValue
319    @Override
320    public Builder<K, V> orderKeysBy(Comparator<? super K> keyComparator) {
321      super.orderKeysBy(keyComparator);
322      return this;
323    }
324
325    /**
326     * {@inheritDoc}
327     *
328     * @since 8.0
329     */
330    @CanIgnoreReturnValue
331    @Override
332    public Builder<K, V> orderValuesBy(Comparator<? super V> valueComparator) {
333      super.orderValuesBy(valueComparator);
334      return this;
335    }
336
337    /** Returns a newly-created immutable list multimap. */
338    @Override
339    public ImmutableListMultimap<K, V> build() {
340      return (ImmutableListMultimap<K, V>) super.build();
341    }
342  }
343
344  /**
345   * Returns an immutable multimap containing the same mappings as {@code multimap}. The generated
346   * multimap's key and value orderings correspond to the iteration ordering of the {@code
347   * multimap.asMap()} view.
348   *
349   * <p>Despite the method name, this method attempts to avoid actually copying the data when it is
350   * safe to do so. The exact circumstances under which a copy will or will not be performed are
351   * undocumented and subject to change.
352   *
353   * @throws NullPointerException if any key or value in {@code multimap} is null
354   */
355  public static <K, V> ImmutableListMultimap<K, V> copyOf(
356      Multimap<? extends K, ? extends V> multimap) {
357    if (multimap.isEmpty()) {
358      return of();
359    }
360
361    // TODO(lowasser): copy ImmutableSetMultimap by using asList() on the sets
362    if (multimap instanceof ImmutableListMultimap) {
363      @SuppressWarnings("unchecked") // safe since multimap is not writable
364      ImmutableListMultimap<K, V> kvMultimap = (ImmutableListMultimap<K, V>) multimap;
365      if (!kvMultimap.isPartialView()) {
366        return kvMultimap;
367      }
368    }
369
370    return fromMapEntries(multimap.asMap().entrySet(), null);
371  }
372
373  /**
374   * Returns an immutable multimap containing the specified entries. The returned multimap iterates
375   * over keys in the order they were first encountered in the input, and the values for each key
376   * are iterated in the order they were encountered.
377   *
378   * @throws NullPointerException if any key, value, or entry is null
379   * @since 19.0
380   */
381  public static <K, V> ImmutableListMultimap<K, V> copyOf(
382      Iterable<? extends Entry<? extends K, ? extends V>> entries) {
383    return new Builder<K, V>().putAll(entries).build();
384  }
385
386  /** Creates an ImmutableListMultimap from an asMap.entrySet. */
387  static <K, V> ImmutableListMultimap<K, V> fromMapEntries(
388      Collection<? extends Map.Entry<? extends K, ? extends Collection<? extends V>>> mapEntries,
389      @Nullable Comparator<? super V> valueComparator) {
390    if (mapEntries.isEmpty()) {
391      return of();
392    }
393    ImmutableMap.Builder<K, ImmutableList<V>> builder =
394        new ImmutableMap.Builder<>(mapEntries.size());
395    int size = 0;
396
397    for (Entry<? extends K, ? extends Collection<? extends V>> entry : mapEntries) {
398      K key = entry.getKey();
399      Collection<? extends V> values = entry.getValue();
400      ImmutableList<V> list =
401          (valueComparator == null)
402              ? ImmutableList.copyOf(values)
403              : ImmutableList.sortedCopyOf(valueComparator, values);
404      if (!list.isEmpty()) {
405        builder.put(key, list);
406        size += list.size();
407      }
408    }
409
410    return new ImmutableListMultimap<>(builder.buildOrThrow(), size);
411  }
412
413  /** Creates an ImmutableListMultimap from an asMap.entrySet. */
414  static <K, V> ImmutableListMultimap<K, V> fromMapBuilderEntries(
415      Collection<? extends Map.Entry<K, ImmutableCollection.Builder<V>>> mapEntries,
416      @Nullable Comparator<? super V> valueComparator) {
417    if (mapEntries.isEmpty()) {
418      return of();
419    }
420    ImmutableMap.Builder<K, ImmutableList<V>> builder =
421        new ImmutableMap.Builder<>(mapEntries.size());
422    int size = 0;
423
424    for (Entry<K, ImmutableCollection.Builder<V>> entry : mapEntries) {
425      K key = entry.getKey();
426      ImmutableList.Builder<V> values = (ImmutableList.Builder<V>) entry.getValue();
427      ImmutableList<V> list =
428          (valueComparator == null) ? values.build() : values.buildSorted(valueComparator);
429      builder.put(key, list);
430      size += list.size();
431    }
432
433    return new ImmutableListMultimap<>(builder.buildOrThrow(), size);
434  }
435
436  /**
437   * An instance created in {@link #readObject} to be returned from {@link #readResolve}. This field
438   * is used only by those methods, and it is never set in a "normal" instance.
439   *
440   * <p>For more background, see {@code ConcurrentHashMultiset.deserializationReplacement}.
441   */
442  private transient @Nullable ImmutableListMultimap<?, ?> deserializationReplacement;
443
444  ImmutableListMultimap(ImmutableMap<K, ImmutableList<V>> map, int size) {
445    super(map, size);
446  }
447
448  // views
449
450  /**
451   * Returns an immutable list of the values for the given key. If no mappings in the multimap have
452   * the provided key, an empty immutable list is returned. The values are in the same order as the
453   * parameters used to build this multimap.
454   */
455  @Override
456  public final ImmutableList<V> get(K key) {
457    // This cast is safe as its type is known in constructor.
458    ImmutableList<V> list = (ImmutableList<V>) map.get(key);
459    return (list == null) ? ImmutableList.of() : list;
460  }
461
462  @LazyInit @RetainedWith private transient @Nullable ImmutableListMultimap<V, K> inverse;
463
464  /**
465   * {@inheritDoc}
466   *
467   * <p>Because an inverse of a list multimap can contain multiple pairs with the same key and
468   * value, this method returns an {@code ImmutableListMultimap} rather than the {@code
469   * ImmutableMultimap} specified in the {@code ImmutableMultimap} class.
470   *
471   * @since 11.0
472   */
473  @Override
474  public final ImmutableListMultimap<V, K> inverse() {
475    ImmutableListMultimap<V, K> result = inverse;
476    if (result == null) {
477      result = inverse = invert();
478    }
479    return result;
480  }
481
482  private ImmutableListMultimap<V, K> invert() {
483    Builder<V, K> builder = builder();
484    for (Entry<K, V> entry : entries()) {
485      builder.put(entry.getValue(), entry.getKey());
486    }
487    ImmutableListMultimap<V, K> invertedMultimap = builder.build();
488    invertedMultimap.inverse = this;
489    return invertedMultimap;
490  }
491
492  /**
493   * Guaranteed to throw an exception and leave the multimap unmodified.
494   *
495   * @throws UnsupportedOperationException always
496   * @deprecated Unsupported operation.
497   */
498  @CanIgnoreReturnValue
499  @Deprecated
500  @Override
501  @DoNotCall("Always throws UnsupportedOperationException")
502  public final ImmutableList<V> removeAll(@Nullable Object key) {
503    throw new UnsupportedOperationException();
504  }
505
506  /**
507   * Guaranteed to throw an exception and leave the multimap unmodified.
508   *
509   * @throws UnsupportedOperationException always
510   * @deprecated Unsupported operation.
511   */
512  @CanIgnoreReturnValue
513  @Deprecated
514  @Override
515  @DoNotCall("Always throws UnsupportedOperationException")
516  public final ImmutableList<V> replaceValues(K key, Iterable<? extends V> values) {
517    throw new UnsupportedOperationException();
518  }
519
520  /**
521   * @serialData number of distinct keys, and then for each distinct key: the key, the number of
522   *     values for that key, and the key's values
523   */
524  @GwtIncompatible
525  @J2ktIncompatible
526    private void writeObject(ObjectOutputStream stream) throws IOException {
527    stream.defaultWriteObject();
528    Serialization.writeMultimap(this, stream);
529  }
530
531  @GwtIncompatible
532  @J2ktIncompatible
533    private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
534    stream.defaultReadObject();
535    int keyCount = stream.readInt();
536    if (keyCount < 0) {
537      throw new InvalidObjectException("Invalid key count " + keyCount);
538    }
539    ImmutableMap.Builder<Object, ImmutableList<Object>> builder = ImmutableMap.builder();
540    int tmpSize = 0;
541
542    for (int i = 0; i < keyCount; i++) {
543      Object key = requireNonNull(stream.readObject());
544      int valueCount = stream.readInt();
545      if (valueCount <= 0) {
546        throw new InvalidObjectException("Invalid value count " + valueCount);
547      }
548
549      ImmutableList.Builder<Object> valuesBuilder = ImmutableList.builder();
550      for (int j = 0; j < valueCount; j++) {
551        valuesBuilder.add(requireNonNull(stream.readObject()));
552      }
553      builder.put(key, valuesBuilder.build());
554      tmpSize += valueCount;
555    }
556
557    ImmutableMap<Object, ImmutableList<Object>> tmpMap;
558    try {
559      tmpMap = builder.buildOrThrow();
560    } catch (IllegalArgumentException e) {
561      throw (InvalidObjectException) new InvalidObjectException(e.getMessage()).initCause(e);
562    }
563
564    deserializationReplacement = new ImmutableListMultimap<>(tmpMap, tmpSize);
565  }
566
567  @GwtIncompatible
568  @J2ktIncompatible
569    private Object readResolve() {
570    return requireNonNull(deserializationReplacement); // set by readObject
571  }
572
573  @GwtIncompatible @J2ktIncompatible private static final long serialVersionUID = 0;
574}