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 21.0
084   */
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 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 = ImmutableListMultimap.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 = ImmutableListMultimap.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 = ImmutableListMultimap.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 = ImmutableListMultimap.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 = ImmutableListMultimap.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   * <pre>{@code
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   * }</pre>
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      @CheckForNull 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      @CheckForNull 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  ImmutableListMultimap(ImmutableMap<K, ImmutableList<V>> map, int size) {
437    super(map, size);
438  }
439
440  // views
441
442  /**
443   * Returns an immutable list of the values for the given key. If no mappings in the multimap have
444   * the provided key, an empty immutable list is returned. The values are in the same order as the
445   * parameters used to build this multimap.
446   */
447  @Override
448  public ImmutableList<V> get(K key) {
449    // This cast is safe as its type is known in constructor.
450    ImmutableList<V> list = (ImmutableList<V>) map.get(key);
451    return (list == null) ? ImmutableList.<V>of() : list;
452  }
453
454  @LazyInit @RetainedWith @CheckForNull private transient ImmutableListMultimap<V, K> inverse;
455
456  /**
457   * {@inheritDoc}
458   *
459   * <p>Because an inverse of a list multimap can contain multiple pairs with the same key and
460   * value, this method returns an {@code ImmutableListMultimap} rather than the {@code
461   * ImmutableMultimap} specified in the {@code ImmutableMultimap} class.
462   *
463   * @since 11.0
464   */
465  @Override
466  public ImmutableListMultimap<V, K> inverse() {
467    ImmutableListMultimap<V, K> result = inverse;
468    return (result == null) ? (inverse = invert()) : result;
469  }
470
471  private ImmutableListMultimap<V, K> invert() {
472    Builder<V, K> builder = builder();
473    for (Entry<K, V> entry : entries()) {
474      builder.put(entry.getValue(), entry.getKey());
475    }
476    ImmutableListMultimap<V, K> invertedMultimap = builder.build();
477    invertedMultimap.inverse = this;
478    return invertedMultimap;
479  }
480
481  /**
482   * Guaranteed to throw an exception and leave the multimap unmodified.
483   *
484   * @throws UnsupportedOperationException always
485   * @deprecated Unsupported operation.
486   */
487  @CanIgnoreReturnValue
488  @Deprecated
489  @Override
490  @DoNotCall("Always throws UnsupportedOperationException")
491  public final ImmutableList<V> removeAll(@CheckForNull Object key) {
492    throw new UnsupportedOperationException();
493  }
494
495  /**
496   * Guaranteed to throw an exception and leave the multimap unmodified.
497   *
498   * @throws UnsupportedOperationException always
499   * @deprecated Unsupported operation.
500   */
501  @CanIgnoreReturnValue
502  @Deprecated
503  @Override
504  @DoNotCall("Always throws UnsupportedOperationException")
505  public final ImmutableList<V> replaceValues(K key, Iterable<? extends V> values) {
506    throw new UnsupportedOperationException();
507  }
508
509  /**
510   * @serialData number of distinct keys, and then for each distinct key: the key, the number of
511   *     values for that key, and the key's values
512   */
513  @GwtIncompatible // java.io.ObjectOutputStream
514  @J2ktIncompatible
515  private void writeObject(ObjectOutputStream stream) throws IOException {
516    stream.defaultWriteObject();
517    Serialization.writeMultimap(this, stream);
518  }
519
520  @GwtIncompatible // java.io.ObjectInputStream
521  @J2ktIncompatible
522  private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
523    stream.defaultReadObject();
524    int keyCount = stream.readInt();
525    if (keyCount < 0) {
526      throw new InvalidObjectException("Invalid key count " + keyCount);
527    }
528    ImmutableMap.Builder<Object, ImmutableList<Object>> builder = ImmutableMap.builder();
529    int tmpSize = 0;
530
531    for (int i = 0; i < keyCount; i++) {
532      Object key = requireNonNull(stream.readObject());
533      int valueCount = stream.readInt();
534      if (valueCount <= 0) {
535        throw new InvalidObjectException("Invalid value count " + valueCount);
536      }
537
538      ImmutableList.Builder<Object> valuesBuilder = ImmutableList.builder();
539      for (int j = 0; j < valueCount; j++) {
540        valuesBuilder.add(requireNonNull(stream.readObject()));
541      }
542      builder.put(key, valuesBuilder.build());
543      tmpSize += valueCount;
544    }
545
546    ImmutableMap<Object, ImmutableList<Object>> tmpMap;
547    try {
548      tmpMap = builder.buildOrThrow();
549    } catch (IllegalArgumentException e) {
550      throw (InvalidObjectException) new InvalidObjectException(e.getMessage()).initCause(e);
551    }
552
553    FieldSettersHolder.MAP_FIELD_SETTER.set(this, tmpMap);
554    FieldSettersHolder.SIZE_FIELD_SETTER.set(this, tmpSize);
555  }
556
557  @GwtIncompatible // Not needed in emulated source
558  @J2ktIncompatible
559  private static final long serialVersionUID = 0;
560}