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