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    @CanIgnoreReturnValue
217    @Override
218    Builder<K, V> combine(ImmutableMultimap.Builder<K, V> other) {
219      super.combine(other);
220      return this;
221    }
222
223    /** Returns a newly-created immutable list multimap. */
224    @Override
225    public ImmutableListMultimap<K, V> build() {
226      return (ImmutableListMultimap<K, V>) super.build();
227    }
228  }
229
230  /**
231   * Returns an immutable multimap containing the same mappings as {@code multimap}. The generated
232   * multimap's key and value orderings correspond to the iteration ordering of the {@code
233   * multimap.asMap()} view.
234   *
235   * <p>Despite the method name, this method attempts to avoid actually copying the data when it is
236   * safe to do so. The exact circumstances under which a copy will or will not be performed are
237   * undocumented and subject to change.
238   *
239   * @throws NullPointerException if any key or value in {@code multimap} is null
240   */
241  public static <K, V> ImmutableListMultimap<K, V> copyOf(
242      Multimap<? extends K, ? extends V> multimap) {
243    if (multimap.isEmpty()) {
244      return of();
245    }
246
247    // TODO(lowasser): copy ImmutableSetMultimap by using asList() on the sets
248    if (multimap instanceof ImmutableListMultimap) {
249      @SuppressWarnings("unchecked") // safe since multimap is not writable
250      ImmutableListMultimap<K, V> kvMultimap = (ImmutableListMultimap<K, V>) multimap;
251      if (!kvMultimap.isPartialView()) {
252        return kvMultimap;
253      }
254    }
255
256    return fromMapEntries(multimap.asMap().entrySet(), null);
257  }
258
259  /**
260   * Returns an immutable multimap containing the specified entries. The returned multimap iterates
261   * over keys in the order they were first encountered in the input, and the values for each key
262   * are iterated in the order they were encountered.
263   *
264   * @throws NullPointerException if any key, value, or entry is null
265   * @since 19.0
266   */
267  @Beta
268  public static <K, V> ImmutableListMultimap<K, V> copyOf(
269      Iterable<? extends Entry<? extends K, ? extends V>> entries) {
270    return new Builder<K, V>().putAll(entries).build();
271  }
272
273  /** Creates an ImmutableListMultimap from an asMap.entrySet. */
274  static <K, V> ImmutableListMultimap<K, V> fromMapEntries(
275      Collection<? extends Map.Entry<? extends K, ? extends Collection<? extends V>>> mapEntries,
276      @NullableDecl Comparator<? super V> valueComparator) {
277    if (mapEntries.isEmpty()) {
278      return of();
279    }
280    ImmutableMap.Builder<K, ImmutableList<V>> builder =
281        new ImmutableMap.Builder<>(mapEntries.size());
282    int size = 0;
283
284    for (Entry<? extends K, ? extends Collection<? extends V>> entry : mapEntries) {
285      K key = entry.getKey();
286      Collection<? extends V> values = entry.getValue();
287      ImmutableList<V> list =
288          (valueComparator == null)
289              ? ImmutableList.copyOf(values)
290              : ImmutableList.sortedCopyOf(valueComparator, values);
291      if (!list.isEmpty()) {
292        builder.put(key, list);
293        size += list.size();
294      }
295    }
296
297    return new ImmutableListMultimap<>(builder.build(), size);
298  }
299
300  ImmutableListMultimap(ImmutableMap<K, ImmutableList<V>> map, int size) {
301    super(map, size);
302  }
303
304  // views
305
306  /**
307   * Returns an immutable list of the values for the given key. If no mappings in the multimap have
308   * the provided key, an empty immutable list is returned. The values are in the same order as the
309   * parameters used to build this multimap.
310   */
311  @Override
312  public ImmutableList<V> get(@NullableDecl K key) {
313    // This cast is safe as its type is known in constructor.
314    ImmutableList<V> list = (ImmutableList<V>) map.get(key);
315    return (list == null) ? ImmutableList.<V>of() : list;
316  }
317
318  @LazyInit @RetainedWith private transient ImmutableListMultimap<V, K> inverse;
319
320  /**
321   * {@inheritDoc}
322   *
323   * <p>Because an inverse of a list multimap can contain multiple pairs with the same key and
324   * value, this method returns an {@code ImmutableListMultimap} rather than the {@code
325   * ImmutableMultimap} specified in the {@code ImmutableMultimap} class.
326   *
327   * @since 11.0
328   */
329  @Override
330  public ImmutableListMultimap<V, K> inverse() {
331    ImmutableListMultimap<V, K> result = inverse;
332    return (result == null) ? (inverse = invert()) : result;
333  }
334
335  private ImmutableListMultimap<V, K> invert() {
336    Builder<V, K> builder = builder();
337    for (Entry<K, V> entry : entries()) {
338      builder.put(entry.getValue(), entry.getKey());
339    }
340    ImmutableListMultimap<V, K> invertedMultimap = builder.build();
341    invertedMultimap.inverse = this;
342    return invertedMultimap;
343  }
344
345  /**
346   * Guaranteed to throw an exception and leave the multimap unmodified.
347   *
348   * @throws UnsupportedOperationException always
349   * @deprecated Unsupported operation.
350   */
351  @CanIgnoreReturnValue
352  @Deprecated
353  @Override
354  public ImmutableList<V> removeAll(Object key) {
355    throw new UnsupportedOperationException();
356  }
357
358  /**
359   * Guaranteed to throw an exception and leave the multimap unmodified.
360   *
361   * @throws UnsupportedOperationException always
362   * @deprecated Unsupported operation.
363   */
364  @CanIgnoreReturnValue
365  @Deprecated
366  @Override
367  public ImmutableList<V> replaceValues(K key, Iterable<? extends V> values) {
368    throw new UnsupportedOperationException();
369  }
370
371  /**
372   * @serialData number of distinct keys, and then for each distinct key: the key, the number of
373   *     values for that key, and the key's values
374   */
375  @GwtIncompatible // java.io.ObjectOutputStream
376  private void writeObject(ObjectOutputStream stream) throws IOException {
377    stream.defaultWriteObject();
378    Serialization.writeMultimap(this, stream);
379  }
380
381  @GwtIncompatible // java.io.ObjectInputStream
382  private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
383    stream.defaultReadObject();
384    int keyCount = stream.readInt();
385    if (keyCount < 0) {
386      throw new InvalidObjectException("Invalid key count " + keyCount);
387    }
388    ImmutableMap.Builder<Object, ImmutableList<Object>> builder = ImmutableMap.builder();
389    int tmpSize = 0;
390
391    for (int i = 0; i < keyCount; i++) {
392      Object key = stream.readObject();
393      int valueCount = stream.readInt();
394      if (valueCount <= 0) {
395        throw new InvalidObjectException("Invalid value count " + valueCount);
396      }
397
398      ImmutableList.Builder<Object> valuesBuilder = ImmutableList.builder();
399      for (int j = 0; j < valueCount; j++) {
400        valuesBuilder.add(stream.readObject());
401      }
402      builder.put(key, valuesBuilder.build());
403      tmpSize += valueCount;
404    }
405
406    ImmutableMap<Object, ImmutableList<Object>> tmpMap;
407    try {
408      tmpMap = builder.build();
409    } catch (IllegalArgumentException e) {
410      throw (InvalidObjectException) new InvalidObjectException(e.getMessage()).initCause(e);
411    }
412
413    FieldSettersHolder.MAP_FIELD_SETTER.set(this, tmpMap);
414    FieldSettersHolder.SIZE_FIELD_SETTER.set(this, tmpSize);
415  }
416
417  @GwtIncompatible // Not needed in emulated source
418  private static final long serialVersionUID = 0;
419}