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