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 {@linkplain java.util.stream#Ordering defined encounter order}, that order
061   * is preserved, but entries are <a href="ImmutableMultimap.html#iteration">grouped by key</a>.
062   *
063   * <p>Example:
064   *
065   * <pre>{@code
066   * static final Multimap<Character, String> FIRST_LETTER_MULTIMAP =
067   *     Stream.of("banana", "apple", "carrot", "asparagus", "cherry")
068   *         .collect(toImmutableListMultimap(str -> str.charAt(0), str -> str.substring(1)));
069   *
070   * // is equivalent to
071   *
072   * static final Multimap<Character, String> FIRST_LETTER_MULTIMAP =
073   *     new ImmutableListMultimap.Builder<Character, String>()
074   *         .put('b', "anana")
075   *         .putAll('a', "pple", "sparagus")
076   *         .putAll('c', "arrot", "herry")
077   *         .build();
078   * }</pre>
079   *
080   * @since 21.0
081   */
082  public static <T, K, V> Collector<T, ?, ImmutableListMultimap<K, V>> toImmutableListMultimap(
083      Function<? super T, ? extends K> keyFunction,
084      Function<? super T, ? extends V> valueFunction) {
085    checkNotNull(keyFunction, "keyFunction");
086    checkNotNull(valueFunction, "valueFunction");
087    return Collector.of(
088        ImmutableListMultimap::<K, V>builder,
089        (builder, t) -> builder.put(keyFunction.apply(t), valueFunction.apply(t)),
090        ImmutableListMultimap.Builder::combine,
091        ImmutableListMultimap.Builder::build);
092  }
093
094  /**
095   * Returns a {@code Collector} accumulating entries into an {@code ImmutableListMultimap}. Each
096   * input element is mapped to a key and a stream of values, each of which are put into the
097   * resulting {@code Multimap}, in the encounter order of the stream and the encounter order of the
098   * streams of values.
099   *
100   * <p>Example:
101   *
102   * <pre>{@code
103   * static final ImmutableListMultimap<Character, Character> FIRST_LETTER_MULTIMAP =
104   *     Stream.of("banana", "apple", "carrot", "asparagus", "cherry")
105   *         .collect(
106   *             flatteningToImmutableListMultimap(
107   *                  str -> str.charAt(0),
108   *                  str -> str.substring(1).chars().mapToObj(c -> (char) c));
109   *
110   * // is equivalent to
111   *
112   * static final ImmutableListMultimap<Character, Character> FIRST_LETTER_MULTIMAP =
113   *     ImmutableListMultimap.<Character, Character>builder()
114   *         .putAll('b', Arrays.asList('a', 'n', 'a', 'n', 'a'))
115   *         .putAll('a', Arrays.asList('p', 'p', 'l', 'e'))
116   *         .putAll('c', Arrays.asList('a', 'r', 'r', 'o', 't'))
117   *         .putAll('a', Arrays.asList('s', 'p', 'a', 'r', 'a', 'g', 'u', 's'))
118   *         .putAll('c', Arrays.asList('h', 'e', 'r', 'r', 'y'))
119   *         .build();
120   * }
121   * }</pre>
122   *
123   * @since 21.0
124   */
125  public static <T, K, V>
126      Collector<T, ?, ImmutableListMultimap<K, V>> flatteningToImmutableListMultimap(
127          Function<? super T, ? extends K> keyFunction,
128          Function<? super T, ? extends Stream<? extends V>> valuesFunction) {
129    checkNotNull(keyFunction);
130    checkNotNull(valuesFunction);
131    return Collectors.collectingAndThen(
132        Multimaps.flatteningToMultimap(
133            input -> checkNotNull(keyFunction.apply(input)),
134            input -> valuesFunction.apply(input).peek(Preconditions::checkNotNull),
135            MultimapBuilder.linkedHashKeys().arrayListValues()::<K, V>build),
136        ImmutableListMultimap::copyOf);
137  }
138
139  /** Returns the empty multimap. */
140  // Casting is safe because the multimap will never hold any elements.
141  @SuppressWarnings("unchecked")
142  public static <K, V> ImmutableListMultimap<K, V> of() {
143    return (ImmutableListMultimap<K, V>) EmptyImmutableListMultimap.INSTANCE;
144  }
145
146  /** Returns an immutable multimap containing a single entry. */
147  public static <K, V> ImmutableListMultimap<K, V> of(K k1, V v1) {
148    ImmutableListMultimap.Builder<K, V> builder = ImmutableListMultimap.builder();
149    builder.put(k1, v1);
150    return builder.build();
151  }
152
153  /** Returns an immutable multimap containing the given entries, in order. */
154  public static <K, V> ImmutableListMultimap<K, V> of(K k1, V v1, K k2, V v2) {
155    ImmutableListMultimap.Builder<K, V> builder = ImmutableListMultimap.builder();
156    builder.put(k1, v1);
157    builder.put(k2, v2);
158    return builder.build();
159  }
160
161  /** Returns an immutable multimap containing the given entries, in order. */
162  public static <K, V> ImmutableListMultimap<K, V> of(K k1, V v1, K k2, V v2, K k3, V v3) {
163    ImmutableListMultimap.Builder<K, V> builder = ImmutableListMultimap.builder();
164    builder.put(k1, v1);
165    builder.put(k2, v2);
166    builder.put(k3, v3);
167    return builder.build();
168  }
169
170  /** Returns an immutable multimap containing the given entries, in order. */
171  public static <K, V> ImmutableListMultimap<K, V> of(
172      K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4) {
173    ImmutableListMultimap.Builder<K, V> builder = ImmutableListMultimap.builder();
174    builder.put(k1, v1);
175    builder.put(k2, v2);
176    builder.put(k3, v3);
177    builder.put(k4, v4);
178    return builder.build();
179  }
180
181  /** Returns an immutable multimap containing the given entries, in order. */
182  public static <K, V> ImmutableListMultimap<K, V> of(
183      K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5) {
184    ImmutableListMultimap.Builder<K, V> builder = ImmutableListMultimap.builder();
185    builder.put(k1, v1);
186    builder.put(k2, v2);
187    builder.put(k3, v3);
188    builder.put(k4, v4);
189    builder.put(k5, v5);
190    return builder.build();
191  }
192
193  // looking for of() with > 5 entries? Use the builder instead.
194
195  /**
196   * Returns a new builder. The generated builder is equivalent to the builder created by the {@link
197   * Builder} constructor.
198   */
199  public static <K, V> Builder<K, V> builder() {
200    return new Builder<>();
201  }
202
203  /**
204   * A builder for creating immutable {@code ListMultimap} instances, especially {@code public
205   * static final} multimaps ("constant multimaps"). Example:
206   *
207   * <pre>{@code
208   * static final Multimap<String, Integer> STRING_TO_INTEGER_MULTIMAP =
209   *     new ImmutableListMultimap.Builder<String, Integer>()
210   *         .put("one", 1)
211   *         .putAll("several", 1, 2, 3)
212   *         .putAll("many", 1, 2, 3, 4, 5)
213   *         .build();
214   * }</pre>
215   *
216   * <p>Builder instances can be reused; it is safe to call {@link #build} multiple times to build
217   * multiple multimaps in series. Each multimap contains the key-value mappings in the previously
218   * created multimaps.
219   *
220   * @since 2.0
221   */
222  public static final class Builder<K, V> extends ImmutableMultimap.Builder<K, V> {
223    /**
224     * Creates a new builder. The returned builder is equivalent to the builder generated by {@link
225     * ImmutableListMultimap#builder}.
226     */
227    public Builder() {}
228
229    @CanIgnoreReturnValue
230    @Override
231    public Builder<K, V> put(K key, V value) {
232      super.put(key, value);
233      return this;
234    }
235
236    /**
237     * {@inheritDoc}
238     *
239     * @since 11.0
240     */
241    @CanIgnoreReturnValue
242    @Override
243    public Builder<K, V> put(Entry<? extends K, ? extends V> entry) {
244      super.put(entry);
245      return this;
246    }
247
248    /**
249     * {@inheritDoc}
250     *
251     * @since 19.0
252     */
253    @CanIgnoreReturnValue
254    @Beta
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  @Beta
358  public static <K, V> ImmutableListMultimap<K, V> copyOf(
359      Iterable<? extends Entry<? extends K, ? extends V>> entries) {
360    return new Builder<K, V>().putAll(entries).build();
361  }
362
363  /** Creates an ImmutableListMultimap from an asMap.entrySet. */
364  static <K, V> ImmutableListMultimap<K, V> fromMapEntries(
365      Collection<? extends Map.Entry<? extends K, ? extends Collection<? extends V>>> mapEntries,
366      @Nullable Comparator<? super V> valueComparator) {
367    if (mapEntries.isEmpty()) {
368      return of();
369    }
370    ImmutableMap.Builder<K, ImmutableList<V>> builder =
371        new ImmutableMap.Builder<>(mapEntries.size());
372    int size = 0;
373
374    for (Entry<? extends K, ? extends Collection<? extends V>> entry : mapEntries) {
375      K key = entry.getKey();
376      Collection<? extends V> values = entry.getValue();
377      ImmutableList<V> list =
378          (valueComparator == null)
379              ? ImmutableList.copyOf(values)
380              : ImmutableList.sortedCopyOf(valueComparator, values);
381      if (!list.isEmpty()) {
382        builder.put(key, list);
383        size += list.size();
384      }
385    }
386
387    return new ImmutableListMultimap<>(builder.build(), size);
388  }
389
390  ImmutableListMultimap(ImmutableMap<K, ImmutableList<V>> map, int size) {
391    super(map, size);
392  }
393
394  // views
395
396  /**
397   * Returns an immutable list of the values for the given key. If no mappings in the multimap have
398   * the provided key, an empty immutable list is returned. The values are in the same order as the
399   * parameters used to build this multimap.
400   */
401  @Override
402  public ImmutableList<V> get(@Nullable K key) {
403    // This cast is safe as its type is known in constructor.
404    ImmutableList<V> list = (ImmutableList<V>) map.get(key);
405    return (list == null) ? ImmutableList.<V>of() : list;
406  }
407
408  @LazyInit @RetainedWith private transient ImmutableListMultimap<V, K> inverse;
409
410  /**
411   * {@inheritDoc}
412   *
413   * <p>Because an inverse of a list multimap can contain multiple pairs with the same key and
414   * value, this method returns an {@code ImmutableListMultimap} rather than the {@code
415   * ImmutableMultimap} specified in the {@code ImmutableMultimap} class.
416   *
417   * @since 11.0
418   */
419  @Override
420  public ImmutableListMultimap<V, K> inverse() {
421    ImmutableListMultimap<V, K> result = inverse;
422    return (result == null) ? (inverse = invert()) : result;
423  }
424
425  private ImmutableListMultimap<V, K> invert() {
426    Builder<V, K> builder = builder();
427    for (Entry<K, V> entry : entries()) {
428      builder.put(entry.getValue(), entry.getKey());
429    }
430    ImmutableListMultimap<V, K> invertedMultimap = builder.build();
431    invertedMultimap.inverse = this;
432    return invertedMultimap;
433  }
434
435  /**
436   * Guaranteed to throw an exception and leave the multimap unmodified.
437   *
438   * @throws UnsupportedOperationException always
439   * @deprecated Unsupported operation.
440   */
441  @CanIgnoreReturnValue
442  @Deprecated
443  @Override
444  public ImmutableList<V> removeAll(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  public ImmutableList<V> replaceValues(K key, Iterable<? extends V> values) {
458    throw new UnsupportedOperationException();
459  }
460
461  /**
462   * @serialData number of distinct keys, and then for each distinct key: the key, the number of
463   *     values for that key, and the key's values
464   */
465  @GwtIncompatible // java.io.ObjectOutputStream
466  private void writeObject(ObjectOutputStream stream) throws IOException {
467    stream.defaultWriteObject();
468    Serialization.writeMultimap(this, stream);
469  }
470
471  @GwtIncompatible // java.io.ObjectInputStream
472  private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
473    stream.defaultReadObject();
474    int keyCount = stream.readInt();
475    if (keyCount < 0) {
476      throw new InvalidObjectException("Invalid key count " + keyCount);
477    }
478    ImmutableMap.Builder<Object, ImmutableList<Object>> builder = ImmutableMap.builder();
479    int tmpSize = 0;
480
481    for (int i = 0; i < keyCount; i++) {
482      Object key = stream.readObject();
483      int valueCount = stream.readInt();
484      if (valueCount <= 0) {
485        throw new InvalidObjectException("Invalid value count " + valueCount);
486      }
487
488      ImmutableList.Builder<Object> valuesBuilder = ImmutableList.builder();
489      for (int j = 0; j < valueCount; j++) {
490        valuesBuilder.add(stream.readObject());
491      }
492      builder.put(key, valuesBuilder.build());
493      tmpSize += valueCount;
494    }
495
496    ImmutableMap<Object, ImmutableList<Object>> tmpMap;
497    try {
498      tmpMap = builder.build();
499    } catch (IllegalArgumentException e) {
500      throw (InvalidObjectException) new InvalidObjectException(e.getMessage()).initCause(e);
501    }
502
503    FieldSettersHolder.MAP_FIELD_SETTER.set(this, tmpMap);
504    FieldSettersHolder.SIZE_FIELD_SETTER.set(this, tmpSize);
505  }
506
507  @GwtIncompatible // Not needed in emulated source
508  private static final long serialVersionUID = 0;
509}