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.base.Preconditions.checkNotNull;
020
021import com.google.common.annotations.Beta;
022import com.google.common.annotations.GwtCompatible;
023import com.google.common.annotations.GwtIncompatible;
024import com.google.common.base.Preconditions;
025import com.google.errorprone.annotations.CanIgnoreReturnValue;
026import com.google.errorprone.annotations.concurrent.LazyInit;
027import com.google.j2objc.annotations.RetainedWith;
028import java.io.IOException;
029import java.io.InvalidObjectException;
030import java.io.ObjectInputStream;
031import java.io.ObjectOutputStream;
032import java.util.Collection;
033import java.util.Comparator;
034import java.util.Map;
035import java.util.Map.Entry;
036import java.util.function.Function;
037import java.util.stream.Collector;
038import java.util.stream.Collectors;
039import java.util.stream.Stream;
040import org.checkerframework.checker.nullness.qual.Nullable;
041
042/**
043 * A {@link ListMultimap} whose contents will never change, with many other important properties
044 * detailed at {@link ImmutableCollection}.
045 *
046 * <p>See the Guava User Guide article on <a href=
047 * "https://github.com/google/guava/wiki/ImmutableCollectionsExplained"> immutable collections</a>.
048 *
049 * @author Jared Levy
050 * @since 2.0
051 */
052@GwtCompatible(serializable = true, emulated = true)
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, K, V> Collector<T, ?, ImmutableListMultimap<K, V>> toImmutableListMultimap(
084      Function<? super T, ? extends K> keyFunction,
085      Function<? super T, ? extends V> valueFunction) {
086    checkNotNull(keyFunction, "keyFunction");
087    checkNotNull(valueFunction, "valueFunction");
088    return Collector.of(
089        ImmutableListMultimap::<K, V>builder,
090        (builder, t) -> builder.put(keyFunction.apply(t), valueFunction.apply(t)),
091        ImmutableListMultimap.Builder::combine,
092        ImmutableListMultimap.Builder::build);
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 21.0
125   */
126  public static <T, 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    checkNotNull(keyFunction);
131    checkNotNull(valuesFunction);
132    return Collectors.collectingAndThen(
133        Multimaps.flatteningToMultimap(
134            input -> checkNotNull(keyFunction.apply(input)),
135            input -> valuesFunction.apply(input).peek(Preconditions::checkNotNull),
136            MultimapBuilder.linkedHashKeys().arrayListValues()::<K, V>build),
137        ImmutableListMultimap::copyOf);
138  }
139
140  /** Returns the empty multimap. */
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    @Beta
256    @Override
257    public Builder<K, V> putAll(Iterable<? extends Entry<? extends K, ? extends V>> entries) {
258      super.putAll(entries);
259      return this;
260    }
261
262    @CanIgnoreReturnValue
263    @Override
264    public Builder<K, V> putAll(K key, Iterable<? extends V> values) {
265      super.putAll(key, values);
266      return this;
267    }
268
269    @CanIgnoreReturnValue
270    @Override
271    public Builder<K, V> putAll(K key, V... values) {
272      super.putAll(key, values);
273      return this;
274    }
275
276    @CanIgnoreReturnValue
277    @Override
278    public Builder<K, V> putAll(Multimap<? extends K, ? extends V> multimap) {
279      super.putAll(multimap);
280      return this;
281    }
282
283    @CanIgnoreReturnValue
284    @Override
285    Builder<K, V> combine(ImmutableMultimap.Builder<K, V> other) {
286      super.combine(other);
287      return this;
288    }
289
290    /**
291     * {@inheritDoc}
292     *
293     * @since 8.0
294     */
295    @CanIgnoreReturnValue
296    @Override
297    public Builder<K, V> orderKeysBy(Comparator<? super K> keyComparator) {
298      super.orderKeysBy(keyComparator);
299      return this;
300    }
301
302    /**
303     * {@inheritDoc}
304     *
305     * @since 8.0
306     */
307    @CanIgnoreReturnValue
308    @Override
309    public Builder<K, V> orderValuesBy(Comparator<? super V> valueComparator) {
310      super.orderValuesBy(valueComparator);
311      return this;
312    }
313
314    /** Returns a newly-created immutable list multimap. */
315    @Override
316    public ImmutableListMultimap<K, V> build() {
317      return (ImmutableListMultimap<K, V>) super.build();
318    }
319  }
320
321  /**
322   * Returns an immutable multimap containing the same mappings as {@code multimap}. The generated
323   * multimap's key and value orderings correspond to the iteration ordering of the {@code
324   * multimap.asMap()} view.
325   *
326   * <p>Despite the method name, this method attempts to avoid actually copying the data when it is
327   * safe to do so. The exact circumstances under which a copy will or will not be performed are
328   * undocumented and subject to change.
329   *
330   * @throws NullPointerException if any key or value in {@code multimap} is null
331   */
332  public static <K, V> ImmutableListMultimap<K, V> copyOf(
333      Multimap<? extends K, ? extends V> multimap) {
334    if (multimap.isEmpty()) {
335      return of();
336    }
337
338    // TODO(lowasser): copy ImmutableSetMultimap by using asList() on the sets
339    if (multimap instanceof ImmutableListMultimap) {
340      @SuppressWarnings("unchecked") // safe since multimap is not writable
341      ImmutableListMultimap<K, V> kvMultimap = (ImmutableListMultimap<K, V>) multimap;
342      if (!kvMultimap.isPartialView()) {
343        return kvMultimap;
344      }
345    }
346
347    return fromMapEntries(multimap.asMap().entrySet(), null);
348  }
349
350  /**
351   * Returns an immutable multimap containing the specified entries. The returned multimap iterates
352   * over keys in the order they were first encountered in the input, and the values for each key
353   * are iterated in the order they were encountered.
354   *
355   * @throws NullPointerException if any key, value, or entry is null
356   * @since 19.0
357   */
358  @Beta
359  public static <K, V> ImmutableListMultimap<K, V> copyOf(
360      Iterable<? extends Entry<? extends K, ? extends V>> entries) {
361    return new Builder<K, V>().putAll(entries).build();
362  }
363
364  /** Creates an ImmutableListMultimap from an asMap.entrySet. */
365  static <K, V> ImmutableListMultimap<K, V> fromMapEntries(
366      Collection<? extends Map.Entry<? extends K, ? extends Collection<? extends V>>> mapEntries,
367      @Nullable Comparator<? super V> valueComparator) {
368    if (mapEntries.isEmpty()) {
369      return of();
370    }
371    ImmutableMap.Builder<K, ImmutableList<V>> builder =
372        new ImmutableMap.Builder<>(mapEntries.size());
373    int size = 0;
374
375    for (Entry<? extends K, ? extends Collection<? extends V>> entry : mapEntries) {
376      K key = entry.getKey();
377      Collection<? extends V> values = entry.getValue();
378      ImmutableList<V> list =
379          (valueComparator == null)
380              ? ImmutableList.copyOf(values)
381              : ImmutableList.sortedCopyOf(valueComparator, values);
382      if (!list.isEmpty()) {
383        builder.put(key, list);
384        size += list.size();
385      }
386    }
387
388    return new ImmutableListMultimap<>(builder.build(), size);
389  }
390
391  ImmutableListMultimap(ImmutableMap<K, ImmutableList<V>> map, int size) {
392    super(map, size);
393  }
394
395  // views
396
397  /**
398   * Returns an immutable list of the values for the given key. If no mappings in the multimap have
399   * the provided key, an empty immutable list is returned. The values are in the same order as the
400   * parameters used to build this multimap.
401   */
402  @Override
403  public ImmutableList<V> get(@Nullable K key) {
404    // This cast is safe as its type is known in constructor.
405    ImmutableList<V> list = (ImmutableList<V>) map.get(key);
406    return (list == null) ? ImmutableList.<V>of() : list;
407  }
408
409  @LazyInit @RetainedWith private transient ImmutableListMultimap<V, K> inverse;
410
411  /**
412   * {@inheritDoc}
413   *
414   * <p>Because an inverse of a list multimap can contain multiple pairs with the same key and
415   * value, this method returns an {@code ImmutableListMultimap} rather than the {@code
416   * ImmutableMultimap} specified in the {@code ImmutableMultimap} class.
417   *
418   * @since 11.0
419   */
420  @Override
421  public ImmutableListMultimap<V, K> inverse() {
422    ImmutableListMultimap<V, K> result = inverse;
423    return (result == null) ? (inverse = invert()) : result;
424  }
425
426  private ImmutableListMultimap<V, K> invert() {
427    Builder<V, K> builder = builder();
428    for (Entry<K, V> entry : entries()) {
429      builder.put(entry.getValue(), entry.getKey());
430    }
431    ImmutableListMultimap<V, K> invertedMultimap = builder.build();
432    invertedMultimap.inverse = this;
433    return invertedMultimap;
434  }
435
436  /**
437   * Guaranteed to throw an exception and leave the multimap unmodified.
438   *
439   * @throws UnsupportedOperationException always
440   * @deprecated Unsupported operation.
441   */
442  @CanIgnoreReturnValue
443  @Deprecated
444  @Override
445  public ImmutableList<V> removeAll(Object key) {
446    throw new UnsupportedOperationException();
447  }
448
449  /**
450   * Guaranteed to throw an exception and leave the multimap unmodified.
451   *
452   * @throws UnsupportedOperationException always
453   * @deprecated Unsupported operation.
454   */
455  @CanIgnoreReturnValue
456  @Deprecated
457  @Override
458  public 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  private void writeObject(ObjectOutputStream stream) throws IOException {
468    stream.defaultWriteObject();
469    Serialization.writeMultimap(this, stream);
470  }
471
472  @GwtIncompatible // java.io.ObjectInputStream
473  private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
474    stream.defaultReadObject();
475    int keyCount = stream.readInt();
476    if (keyCount < 0) {
477      throw new InvalidObjectException("Invalid key count " + keyCount);
478    }
479    ImmutableMap.Builder<Object, ImmutableList<Object>> builder = ImmutableMap.builder();
480    int tmpSize = 0;
481
482    for (int i = 0; i < keyCount; i++) {
483      Object key = stream.readObject();
484      int valueCount = stream.readInt();
485      if (valueCount <= 0) {
486        throw new InvalidObjectException("Invalid value count " + valueCount);
487      }
488
489      ImmutableList.Builder<Object> valuesBuilder = ImmutableList.builder();
490      for (int j = 0; j < valueCount; j++) {
491        valuesBuilder.add(stream.readObject());
492      }
493      builder.put(key, valuesBuilder.build());
494      tmpSize += valueCount;
495    }
496
497    ImmutableMap<Object, ImmutableList<Object>> tmpMap;
498    try {
499      tmpMap = builder.build();
500    } catch (IllegalArgumentException e) {
501      throw (InvalidObjectException) new InvalidObjectException(e.getMessage()).initCause(e);
502    }
503
504    FieldSettersHolder.MAP_FIELD_SETTER.set(this, tmpMap);
505    FieldSettersHolder.SIZE_FIELD_SETTER.set(this, tmpSize);
506  }
507
508  @GwtIncompatible // Not needed in emulated source
509  private static final long serialVersionUID = 0;
510}