• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2008 The Guava Authors
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package com.google.common.collect;
18 
19 
20 import com.google.common.annotations.Beta;
21 import com.google.common.annotations.GwtCompatible;
22 import com.google.common.annotations.GwtIncompatible;
23 import com.google.errorprone.annotations.CanIgnoreReturnValue;
24 import com.google.errorprone.annotations.DoNotCall;
25 import com.google.errorprone.annotations.concurrent.LazyInit;
26 import com.google.j2objc.annotations.RetainedWith;
27 import java.io.IOException;
28 import java.io.InvalidObjectException;
29 import java.io.ObjectInputStream;
30 import java.io.ObjectOutputStream;
31 import java.util.Collection;
32 import java.util.Comparator;
33 import java.util.Map;
34 import java.util.Map.Entry;
35 import java.util.function.Function;
36 import java.util.stream.Collector;
37 import java.util.stream.Stream;
38 import javax.annotation.CheckForNull;
39 import org.checkerframework.checker.nullness.qual.Nullable;
40 
41 /**
42  * A {@link ListMultimap} whose contents will never change, with many other important properties
43  * detailed at {@link ImmutableCollection}.
44  *
45  * <p>See the Guava User Guide article on <a href=
46  * "https://github.com/google/guava/wiki/ImmutableCollectionsExplained"> immutable collections</a>.
47  *
48  * @author Jared Levy
49  * @since 2.0
50  */
51 @GwtCompatible(serializable = true, emulated = true)
52 @ElementTypesAreNonnullByDefault
53 public class ImmutableListMultimap<K, V> extends ImmutableMultimap<K, V>
54     implements ListMultimap<K, V> {
55   /**
56    * Returns a {@link Collector} that accumulates elements into an {@code ImmutableListMultimap}
57    * whose keys and values are the result of applying the provided mapping functions to the input
58    * elements.
59    *
60    * <p>For streams with defined encounter order (as defined in the Ordering section of the {@link
61    * java.util.stream} Javadoc), that order is preserved, but entries are <a
62    * href="ImmutableMultimap.html#iteration">grouped by key</a>.
63    *
64    * <p>Example:
65    *
66    * <pre>{@code
67    * static final Multimap<Character, String> FIRST_LETTER_MULTIMAP =
68    *     Stream.of("banana", "apple", "carrot", "asparagus", "cherry")
69    *         .collect(toImmutableListMultimap(str -> str.charAt(0), str -> str.substring(1)));
70    *
71    * // is equivalent to
72    *
73    * static final Multimap<Character, String> FIRST_LETTER_MULTIMAP =
74    *     new ImmutableListMultimap.Builder<Character, String>()
75    *         .put('b', "anana")
76    *         .putAll('a', "pple", "sparagus")
77    *         .putAll('c', "arrot", "herry")
78    *         .build();
79    * }</pre>
80    *
81    * @since 21.0
82    */
83   public static <T extends @Nullable Object, K, V>
toImmutableListMultimap( Function<? super T, ? extends K> keyFunction, Function<? super T, ? extends V> valueFunction)84       Collector<T, ?, ImmutableListMultimap<K, V>> toImmutableListMultimap(
85           Function<? super T, ? extends K> keyFunction,
86           Function<? super T, ? extends V> valueFunction) {
87     return CollectCollectors.toImmutableListMultimap(keyFunction, valueFunction);
88   }
89 
90   /**
91    * Returns a {@code Collector} accumulating entries into an {@code ImmutableListMultimap}. Each
92    * input element is mapped to a key and a stream of values, each of which are put into the
93    * resulting {@code Multimap}, in the encounter order of the stream and the encounter order of the
94    * streams of values.
95    *
96    * <p>Example:
97    *
98    * <pre>{@code
99    * static final ImmutableListMultimap<Character, Character> FIRST_LETTER_MULTIMAP =
100    *     Stream.of("banana", "apple", "carrot", "asparagus", "cherry")
101    *         .collect(
102    *             flatteningToImmutableListMultimap(
103    *                  str -> str.charAt(0),
104    *                  str -> str.substring(1).chars().mapToObj(c -> (char) c));
105    *
106    * // is equivalent to
107    *
108    * static final ImmutableListMultimap<Character, Character> FIRST_LETTER_MULTIMAP =
109    *     ImmutableListMultimap.<Character, Character>builder()
110    *         .putAll('b', Arrays.asList('a', 'n', 'a', 'n', 'a'))
111    *         .putAll('a', Arrays.asList('p', 'p', 'l', 'e'))
112    *         .putAll('c', Arrays.asList('a', 'r', 'r', 'o', 't'))
113    *         .putAll('a', Arrays.asList('s', 'p', 'a', 'r', 'a', 'g', 'u', 's'))
114    *         .putAll('c', Arrays.asList('h', 'e', 'r', 'r', 'y'))
115    *         .build();
116    * }
117    * }</pre>
118    *
119    * @since 21.0
120    */
121   public static <T extends @Nullable Object, K, V>
flatteningToImmutableListMultimap( Function<? super T, ? extends K> keyFunction, Function<? super T, ? extends Stream<? extends V>> valuesFunction)122       Collector<T, ?, ImmutableListMultimap<K, V>> flatteningToImmutableListMultimap(
123           Function<? super T, ? extends K> keyFunction,
124           Function<? super T, ? extends Stream<? extends V>> valuesFunction) {
125     return CollectCollectors.flatteningToImmutableListMultimap(keyFunction, valuesFunction);
126   }
127 
128   /**
129    * Returns the empty multimap.
130    *
131    * <p><b>Performance note:</b> the instance returned is a singleton.
132    */
133   // Casting is safe because the multimap will never hold any elements.
134   @SuppressWarnings("unchecked")
of()135   public static <K, V> ImmutableListMultimap<K, V> of() {
136     return (ImmutableListMultimap<K, V>) EmptyImmutableListMultimap.INSTANCE;
137   }
138 
139   /** Returns an immutable multimap containing a single entry. */
of(K k1, V v1)140   public static <K, V> ImmutableListMultimap<K, V> of(K k1, V v1) {
141     ImmutableListMultimap.Builder<K, V> builder = ImmutableListMultimap.builder();
142     builder.put(k1, v1);
143     return builder.build();
144   }
145 
146   /** Returns an immutable multimap containing the given entries, in order. */
of(K k1, V v1, K k2, V v2)147   public static <K, V> ImmutableListMultimap<K, V> of(K k1, V v1, K k2, V v2) {
148     ImmutableListMultimap.Builder<K, V> builder = ImmutableListMultimap.builder();
149     builder.put(k1, v1);
150     builder.put(k2, v2);
151     return builder.build();
152   }
153 
154   /** Returns an immutable multimap containing the given entries, in order. */
of(K k1, V v1, K k2, V v2, K k3, V v3)155   public static <K, V> ImmutableListMultimap<K, V> of(K k1, V v1, K k2, V v2, K k3, V v3) {
156     ImmutableListMultimap.Builder<K, V> builder = ImmutableListMultimap.builder();
157     builder.put(k1, v1);
158     builder.put(k2, v2);
159     builder.put(k3, v3);
160     return builder.build();
161   }
162 
163   /** Returns an immutable multimap containing the given entries, in order. */
of( K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4)164   public static <K, V> ImmutableListMultimap<K, V> of(
165       K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4) {
166     ImmutableListMultimap.Builder<K, V> builder = ImmutableListMultimap.builder();
167     builder.put(k1, v1);
168     builder.put(k2, v2);
169     builder.put(k3, v3);
170     builder.put(k4, v4);
171     return builder.build();
172   }
173 
174   /** Returns an immutable multimap containing the given entries, in order. */
of( K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5)175   public static <K, V> ImmutableListMultimap<K, V> of(
176       K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5) {
177     ImmutableListMultimap.Builder<K, V> builder = ImmutableListMultimap.builder();
178     builder.put(k1, v1);
179     builder.put(k2, v2);
180     builder.put(k3, v3);
181     builder.put(k4, v4);
182     builder.put(k5, v5);
183     return builder.build();
184   }
185 
186   // looking for of() with > 5 entries? Use the builder instead.
187 
188   /**
189    * Returns a new builder. The generated builder is equivalent to the builder created by the {@link
190    * Builder} constructor.
191    */
builder()192   public static <K, V> Builder<K, V> builder() {
193     return new Builder<>();
194   }
195 
196   /**
197    * A builder for creating immutable {@code ListMultimap} instances, especially {@code public
198    * static final} multimaps ("constant multimaps"). Example:
199    *
200    * <pre>{@code
201    * static final Multimap<String, Integer> STRING_TO_INTEGER_MULTIMAP =
202    *     new ImmutableListMultimap.Builder<String, Integer>()
203    *         .put("one", 1)
204    *         .putAll("several", 1, 2, 3)
205    *         .putAll("many", 1, 2, 3, 4, 5)
206    *         .build();
207    * }</pre>
208    *
209    * <p>Builder instances can be reused; it is safe to call {@link #build} multiple times to build
210    * multiple multimaps in series. Each multimap contains the key-value mappings in the previously
211    * created multimaps.
212    *
213    * @since 2.0
214    */
215   public static final class Builder<K, V> extends ImmutableMultimap.Builder<K, V> {
216     /**
217      * Creates a new builder. The returned builder is equivalent to the builder generated by {@link
218      * ImmutableListMultimap#builder}.
219      */
Builder()220     public Builder() {}
221 
222     @CanIgnoreReturnValue
223     @Override
put(K key, V value)224     public Builder<K, V> put(K key, V value) {
225       super.put(key, value);
226       return this;
227     }
228 
229     /**
230      * {@inheritDoc}
231      *
232      * @since 11.0
233      */
234     @CanIgnoreReturnValue
235     @Override
put(Entry<? extends K, ? extends V> entry)236     public Builder<K, V> put(Entry<? extends K, ? extends V> entry) {
237       super.put(entry);
238       return this;
239     }
240 
241     /**
242      * {@inheritDoc}
243      *
244      * @since 19.0
245      */
246     @CanIgnoreReturnValue
247     @Beta
248     @Override
putAll(Iterable<? extends Entry<? extends K, ? extends V>> entries)249     public Builder<K, V> putAll(Iterable<? extends Entry<? extends K, ? extends V>> entries) {
250       super.putAll(entries);
251       return this;
252     }
253 
254     @CanIgnoreReturnValue
255     @Override
putAll(K key, Iterable<? extends V> values)256     public Builder<K, V> putAll(K key, Iterable<? extends V> values) {
257       super.putAll(key, values);
258       return this;
259     }
260 
261     @CanIgnoreReturnValue
262     @Override
putAll(K key, V... values)263     public Builder<K, V> putAll(K key, V... values) {
264       super.putAll(key, values);
265       return this;
266     }
267 
268     @CanIgnoreReturnValue
269     @Override
putAll(Multimap<? extends K, ? extends V> multimap)270     public Builder<K, V> putAll(Multimap<? extends K, ? extends V> multimap) {
271       super.putAll(multimap);
272       return this;
273     }
274 
275     @CanIgnoreReturnValue
276     @Override
combine(ImmutableMultimap.Builder<K, V> other)277     Builder<K, V> combine(ImmutableMultimap.Builder<K, V> other) {
278       super.combine(other);
279       return this;
280     }
281 
282     /**
283      * {@inheritDoc}
284      *
285      * @since 8.0
286      */
287     @CanIgnoreReturnValue
288     @Override
orderKeysBy(Comparator<? super K> keyComparator)289     public Builder<K, V> orderKeysBy(Comparator<? super K> keyComparator) {
290       super.orderKeysBy(keyComparator);
291       return this;
292     }
293 
294     /**
295      * {@inheritDoc}
296      *
297      * @since 8.0
298      */
299     @CanIgnoreReturnValue
300     @Override
orderValuesBy(Comparator<? super V> valueComparator)301     public Builder<K, V> orderValuesBy(Comparator<? super V> valueComparator) {
302       super.orderValuesBy(valueComparator);
303       return this;
304     }
305 
306     /** Returns a newly-created immutable list multimap. */
307     @Override
build()308     public ImmutableListMultimap<K, V> build() {
309       return (ImmutableListMultimap<K, V>) super.build();
310     }
311   }
312 
313   /**
314    * Returns an immutable multimap containing the same mappings as {@code multimap}. The generated
315    * multimap's key and value orderings correspond to the iteration ordering of the {@code
316    * multimap.asMap()} view.
317    *
318    * <p>Despite the method name, this method attempts to avoid actually copying the data when it is
319    * safe to do so. The exact circumstances under which a copy will or will not be performed are
320    * undocumented and subject to change.
321    *
322    * @throws NullPointerException if any key or value in {@code multimap} is null
323    */
copyOf( Multimap<? extends K, ? extends V> multimap)324   public static <K, V> ImmutableListMultimap<K, V> copyOf(
325       Multimap<? extends K, ? extends V> multimap) {
326     if (multimap.isEmpty()) {
327       return of();
328     }
329 
330     // TODO(lowasser): copy ImmutableSetMultimap by using asList() on the sets
331     if (multimap instanceof ImmutableListMultimap) {
332       @SuppressWarnings("unchecked") // safe since multimap is not writable
333       ImmutableListMultimap<K, V> kvMultimap = (ImmutableListMultimap<K, V>) multimap;
334       if (!kvMultimap.isPartialView()) {
335         return kvMultimap;
336       }
337     }
338 
339     return fromMapEntries(multimap.asMap().entrySet(), null);
340   }
341 
342   /**
343    * Returns an immutable multimap containing the specified entries. The returned multimap iterates
344    * over keys in the order they were first encountered in the input, and the values for each key
345    * are iterated in the order they were encountered.
346    *
347    * @throws NullPointerException if any key, value, or entry is null
348    * @since 19.0
349    */
350   @Beta
copyOf( Iterable<? extends Entry<? extends K, ? extends V>> entries)351   public static <K, V> ImmutableListMultimap<K, V> copyOf(
352       Iterable<? extends Entry<? extends K, ? extends V>> entries) {
353     return new Builder<K, V>().putAll(entries).build();
354   }
355 
356   /** Creates an ImmutableListMultimap from an asMap.entrySet. */
fromMapEntries( Collection<? extends Map.Entry<? extends K, ? extends Collection<? extends V>>> mapEntries, @Nullable Comparator<? super V> valueComparator)357   static <K, V> ImmutableListMultimap<K, V> fromMapEntries(
358       Collection<? extends Map.Entry<? extends K, ? extends Collection<? extends V>>> mapEntries,
359       @Nullable Comparator<? super V> valueComparator) {
360     if (mapEntries.isEmpty()) {
361       return of();
362     }
363     ImmutableMap.Builder<K, ImmutableList<V>> builder =
364         new ImmutableMap.Builder<>(mapEntries.size());
365     int size = 0;
366 
367     for (Entry<? extends K, ? extends Collection<? extends V>> entry : mapEntries) {
368       K key = entry.getKey();
369       Collection<? extends V> values = entry.getValue();
370       ImmutableList<V> list =
371           (valueComparator == null)
372               ? ImmutableList.copyOf(values)
373               : ImmutableList.sortedCopyOf(valueComparator, values);
374       if (!list.isEmpty()) {
375         builder.put(key, list);
376         size += list.size();
377       }
378     }
379 
380     return new ImmutableListMultimap<>(builder.build(), size);
381   }
382 
ImmutableListMultimap(ImmutableMap<K, ImmutableList<V>> map, int size)383   ImmutableListMultimap(ImmutableMap<K, ImmutableList<V>> map, int size) {
384     super(map, size);
385   }
386 
387   // views
388 
389   /**
390    * Returns an immutable list of the values for the given key. If no mappings in the multimap have
391    * the provided key, an empty immutable list is returned. The values are in the same order as the
392    * parameters used to build this multimap.
393    */
394   @Override
get(K key)395   public ImmutableList<V> get(K key) {
396     // This cast is safe as its type is known in constructor.
397     ImmutableList<V> list = (ImmutableList<V>) map.get(key);
398     return (list == null) ? ImmutableList.<V>of() : list;
399   }
400 
401   @LazyInit @RetainedWith @CheckForNull private transient ImmutableListMultimap<V, K> inverse;
402 
403   /**
404    * {@inheritDoc}
405    *
406    * <p>Because an inverse of a list multimap can contain multiple pairs with the same key and
407    * value, this method returns an {@code ImmutableListMultimap} rather than the {@code
408    * ImmutableMultimap} specified in the {@code ImmutableMultimap} class.
409    *
410    * @since 11.0
411    */
412   @Override
inverse()413   public ImmutableListMultimap<V, K> inverse() {
414     ImmutableListMultimap<V, K> result = inverse;
415     return (result == null) ? (inverse = invert()) : result;
416   }
417 
invert()418   private ImmutableListMultimap<V, K> invert() {
419     Builder<V, K> builder = builder();
420     for (Entry<K, V> entry : entries()) {
421       builder.put(entry.getValue(), entry.getKey());
422     }
423     ImmutableListMultimap<V, K> invertedMultimap = builder.build();
424     invertedMultimap.inverse = this;
425     return invertedMultimap;
426   }
427 
428   /**
429    * Guaranteed to throw an exception and leave the multimap unmodified.
430    *
431    * @throws UnsupportedOperationException always
432    * @deprecated Unsupported operation.
433    */
434   @CanIgnoreReturnValue
435   @Deprecated
436   @Override
437   @DoNotCall("Always throws UnsupportedOperationException")
removeAll(@heckForNull Object key)438   public final ImmutableList<V> removeAll(@CheckForNull Object key) {
439     throw new UnsupportedOperationException();
440   }
441 
442   /**
443    * Guaranteed to throw an exception and leave the multimap unmodified.
444    *
445    * @throws UnsupportedOperationException always
446    * @deprecated Unsupported operation.
447    */
448   @CanIgnoreReturnValue
449   @Deprecated
450   @Override
451   @DoNotCall("Always throws UnsupportedOperationException")
replaceValues(K key, Iterable<? extends V> values)452   public final ImmutableList<V> replaceValues(K key, Iterable<? extends V> values) {
453     throw new UnsupportedOperationException();
454   }
455 
456   /**
457    * @serialData number of distinct keys, and then for each distinct key: the key, the number of
458    *     values for that key, and the key's values
459    */
460   @GwtIncompatible // java.io.ObjectOutputStream
writeObject(ObjectOutputStream stream)461   private void writeObject(ObjectOutputStream stream) throws IOException {
462     stream.defaultWriteObject();
463     Serialization.writeMultimap(this, stream);
464   }
465 
466   @GwtIncompatible // java.io.ObjectInputStream
readObject(ObjectInputStream stream)467   private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
468     stream.defaultReadObject();
469     int keyCount = stream.readInt();
470     if (keyCount < 0) {
471       throw new InvalidObjectException("Invalid key count " + keyCount);
472     }
473     ImmutableMap.Builder<Object, ImmutableList<Object>> builder = ImmutableMap.builder();
474     int tmpSize = 0;
475 
476     for (int i = 0; i < keyCount; i++) {
477       Object key = stream.readObject();
478       int valueCount = stream.readInt();
479       if (valueCount <= 0) {
480         throw new InvalidObjectException("Invalid value count " + valueCount);
481       }
482 
483       ImmutableList.Builder<Object> valuesBuilder = ImmutableList.builder();
484       for (int j = 0; j < valueCount; j++) {
485         valuesBuilder.add(stream.readObject());
486       }
487       builder.put(key, valuesBuilder.build());
488       tmpSize += valueCount;
489     }
490 
491     ImmutableMap<Object, ImmutableList<Object>> tmpMap;
492     try {
493       tmpMap = builder.build();
494     } catch (IllegalArgumentException e) {
495       throw (InvalidObjectException) new InvalidObjectException(e.getMessage()).initCause(e);
496     }
497 
498     FieldSettersHolder.MAP_FIELD_SETTER.set(this, tmpMap);
499     FieldSettersHolder.SIZE_FIELD_SETTER.set(this, tmpSize);
500   }
501 
502   @GwtIncompatible // Not needed in emulated source
503   private static final long serialVersionUID = 0;
504 }
505