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