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