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