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