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