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