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