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