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