001/*
002 * Copyright (C) 2007 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.errorprone.annotations.CanIgnoreReturnValue;
021import com.google.errorprone.annotations.CompatibleWith;
022import java.util.Collection;
023import java.util.List;
024import java.util.Map;
025import java.util.Map.Entry;
026import java.util.Set;
027import org.checkerframework.checker.nullness.compatqual.NullableDecl;
028
029/**
030 * A collection that maps keys to values, similar to {@link Map}, but in which each key may be
031 * associated with <i>multiple</i> values. You can visualize the contents of a multimap either as a
032 * map from keys to <i>nonempty</i> collections of values:
033 *
034 * <ul>
035 *   <li>a → 1, 2
036 *   <li>b → 3
037 * </ul>
038 *
039 * ... or as a single "flattened" collection of key-value pairs:
040 *
041 * <ul>
042 *   <li>a → 1
043 *   <li>a → 2
044 *   <li>b → 3
045 * </ul>
046 *
047 * <p><b>Important:</b> although the first interpretation resembles how most multimaps are
048 * <i>implemented</i>, the design of the {@code Multimap} API is based on the <i>second</i> form.
049 * So, using the multimap shown above as an example, the {@link #size} is {@code 3}, not {@code 2},
050 * and the {@link #values} collection is {@code [1, 2, 3]}, not {@code [[1, 2], [3]]}. For those
051 * times when the first style is more useful, use the multimap's {@link #asMap} view (or create a
052 * {@code Map<K, Collection<V>>} in the first place).
053 *
054 * <h3>Example</h3>
055 *
056 * <p>The following code:
057 *
058 * <pre>{@code
059 * ListMultimap<String, String> multimap = ArrayListMultimap.create();
060 * for (President pres : US_PRESIDENTS_IN_ORDER) {
061 *   multimap.put(pres.firstName(), pres.lastName());
062 * }
063 * for (String firstName : multimap.keySet()) {
064 *   List<String> lastNames = multimap.get(firstName);
065 *   out.println(firstName + ": " + lastNames);
066 * }
067 * }</pre>
068 *
069 * ... produces output such as:
070 *
071 * <pre>{@code
072 * Zachary: [Taylor]
073 * John: [Adams, Adams, Tyler, Kennedy]  // Remember, Quincy!
074 * George: [Washington, Bush, Bush]
075 * Grover: [Cleveland, Cleveland]        // Two, non-consecutive terms, rep'ing NJ!
076 * ...
077 * }</pre>
078 *
079 * <h3>Views</h3>
080 *
081 * <p>Much of the power of the multimap API comes from the <i>view collections</i> it provides.
082 * These always reflect the latest state of the multimap itself. When they support modification, the
083 * changes are <i>write-through</i> (they automatically update the backing multimap). These view
084 * collections are:
085 *
086 * <ul>
087 *   <li>{@link #asMap}, mentioned above
088 *   <li>{@link #keys}, {@link #keySet}, {@link #values}, {@link #entries}, which are similar to the
089 *       corresponding view collections of {@link Map}
090 *   <li>and, notably, even the collection returned by {@link #get get(key)} is an active view of
091 *       the values corresponding to {@code key}
092 * </ul>
093 *
094 * <p>The collections returned by the {@link #replaceValues replaceValues} and {@link #removeAll
095 * removeAll} methods, which contain values that have just been removed from the multimap, are
096 * naturally <i>not</i> views.
097 *
098 * <h3>Subinterfaces</h3>
099 *
100 * <p>Instead of using the {@code Multimap} interface directly, prefer the subinterfaces {@link
101 * ListMultimap} and {@link SetMultimap}. These take their names from the fact that the collections
102 * they return from {@code get} behave like (and, of course, implement) {@link List} and {@link
103 * Set}, respectively.
104 *
105 * <p>For example, the "presidents" code snippet above used a {@code ListMultimap}; if it had used a
106 * {@code SetMultimap} instead, two presidents would have vanished, and last names might or might
107 * not appear in chronological order.
108 *
109 * <p><b>Warning:</b> instances of type {@code Multimap} may not implement {@link Object#equals} in
110 * the way you expect. Multimaps containing the same key-value pairs, even in the same order, may or
111 * may not be equal and may or may not have the same {@code hashCode}. The recommended subinterfaces
112 * provide much stronger guarantees.
113 *
114 * <h3>Comparison to a map of collections</h3>
115 *
116 * <p>Multimaps are commonly used in places where a {@code Map<K, Collection<V>>} would otherwise
117 * have appeared. The differences include:
118 *
119 * <ul>
120 *   <li>There is no need to populate an empty collection before adding an entry with {@link #put
121 *       put}.
122 *   <li>{@code get} never returns {@code null}, only an empty collection.
123 *   <li>A key is contained in the multimap if and only if it maps to at least one value. Any
124 *       operation that causes a key to have zero associated values has the effect of
125 *       <i>removing</i> that key from the multimap.
126 *   <li>The total entry count is available as {@link #size}.
127 *   <li>Many complex operations become easier; for example, {@code
128 *       Collections.min(multimap.values())} finds the smallest value across all keys.
129 * </ul>
130 *
131 * <h3>Implementations</h3>
132 *
133 * <p>As always, prefer the immutable implementations, {@link ImmutableListMultimap} and {@link
134 * ImmutableSetMultimap}. General-purpose mutable implementations are listed above under "All Known
135 * Implementing Classes". You can also create a <i>custom</i> multimap, backed by any {@code Map}
136 * and {@link Collection} types, using the {@link Multimaps#newMultimap Multimaps.newMultimap}
137 * family of methods. Finally, another popular way to obtain a multimap is using {@link
138 * Multimaps#index Multimaps.index}. See the {@link Multimaps} class for these and other static
139 * utilities related to multimaps.
140 *
141 * <h3>Other Notes</h3>
142 *
143 * <p>As with {@code Map}, the behavior of a {@code Multimap} is not specified if key objects
144 * already present in the multimap change in a manner that affects {@code equals} comparisons. Use
145 * caution if mutable objects are used as keys in a {@code Multimap}.
146 *
147 * <p>All methods that modify the multimap are optional. The view collections returned by the
148 * multimap may or may not be modifiable. Any modification method that is not supported will throw
149 * {@link UnsupportedOperationException}.
150 *
151 * <p>See the Guava User Guide article on <a href=
152 * "https://github.com/google/guava/wiki/NewCollectionTypesExplained#multimap"> {@code
153 * Multimap}</a>.
154 *
155 * @author Jared Levy
156 * @since 2.0
157 */
158@GwtCompatible
159public interface Multimap<K, V> {
160  // Query Operations
161
162  /**
163   * Returns the number of key-value pairs in this multimap.
164   *
165   * <p><b>Note:</b> this method does not return the number of <i>distinct keys</i> in the multimap,
166   * which is given by {@code keySet().size()} or {@code asMap().size()}. See the opening section of
167   * the {@link Multimap} class documentation for clarification.
168   */
169  int size();
170
171  /**
172   * Returns {@code true} if this multimap contains no key-value pairs. Equivalent to {@code size()
173   * == 0}, but can in some cases be more efficient.
174   */
175  boolean isEmpty();
176
177  /**
178   * Returns {@code true} if this multimap contains at least one key-value pair with the key {@code
179   * key}.
180   */
181  boolean containsKey(@CompatibleWith("K") @NullableDecl Object key);
182
183  /**
184   * Returns {@code true} if this multimap contains at least one key-value pair with the value
185   * {@code value}.
186   */
187  boolean containsValue(@CompatibleWith("V") @NullableDecl Object value);
188
189  /**
190   * Returns {@code true} if this multimap contains at least one key-value pair with the key {@code
191   * key} and the value {@code value}.
192   */
193  boolean containsEntry(
194      @CompatibleWith("K") @NullableDecl Object key,
195      @CompatibleWith("V") @NullableDecl Object value);
196
197  // Modification Operations
198
199  /**
200   * Stores a key-value pair in this multimap.
201   *
202   * <p>Some multimap implementations allow duplicate key-value pairs, in which case {@code put}
203   * always adds a new key-value pair and increases the multimap size by 1. Other implementations
204   * prohibit duplicates, and storing a key-value pair that's already in the multimap has no effect.
205   *
206   * @return {@code true} if the method increased the size of the multimap, or {@code false} if the
207   *     multimap already contained the key-value pair and doesn't allow duplicates
208   */
209  @CanIgnoreReturnValue
210  boolean put(@NullableDecl K key, @NullableDecl V value);
211
212  /**
213   * Removes a single key-value pair with the key {@code key} and the value {@code value} from this
214   * multimap, if such exists. If multiple key-value pairs in the multimap fit this description,
215   * which one is removed is unspecified.
216   *
217   * @return {@code true} if the multimap changed
218   */
219  @CanIgnoreReturnValue
220  boolean remove(
221      @CompatibleWith("K") @NullableDecl Object key,
222      @CompatibleWith("V") @NullableDecl Object value);
223
224  // Bulk Operations
225
226  /**
227   * Stores a key-value pair in this multimap for each of {@code values}, all using the same key,
228   * {@code key}. Equivalent to (but expected to be more efficient than):
229   *
230   * <pre>{@code
231   * for (V value : values) {
232   *   put(key, value);
233   * }
234   * }</pre>
235   *
236   * <p>In particular, this is a no-op if {@code values} is empty.
237   *
238   * @return {@code true} if the multimap changed
239   */
240  @CanIgnoreReturnValue
241  boolean putAll(@NullableDecl K key, Iterable<? extends V> values);
242
243  /**
244   * Stores all key-value pairs of {@code multimap} in this multimap, in the order returned by
245   * {@code multimap.entries()}.
246   *
247   * @return {@code true} if the multimap changed
248   */
249  @CanIgnoreReturnValue
250  boolean putAll(Multimap<? extends K, ? extends V> multimap);
251
252  /**
253   * Stores a collection of values with the same key, replacing any existing values for that key.
254   *
255   * <p>If {@code values} is empty, this is equivalent to {@link #removeAll(Object) removeAll(key)}.
256   *
257   * @return the collection of replaced values, or an empty collection if no values were previously
258   *     associated with the key. The collection <i>may</i> be modifiable, but updating it will have
259   *     no effect on the multimap.
260   */
261  @CanIgnoreReturnValue
262  Collection<V> replaceValues(@NullableDecl K key, Iterable<? extends V> values);
263
264  /**
265   * Removes all values associated with the key {@code key}.
266   *
267   * <p>Once this method returns, {@code key} will not be mapped to any values, so it will not
268   * appear in {@link #keySet()}, {@link #asMap()}, or any other views.
269   *
270   * @return the values that were removed (possibly empty). The returned collection <i>may</i> be
271   *     modifiable, but updating it will have no effect on the multimap.
272   */
273  @CanIgnoreReturnValue
274  Collection<V> removeAll(@CompatibleWith("K") @NullableDecl Object key);
275
276  /** Removes all key-value pairs from the multimap, leaving it {@linkplain #isEmpty empty}. */
277  void clear();
278
279  // Views
280
281  /**
282   * Returns a view collection of the values associated with {@code key} in this multimap, if any.
283   * Note that when {@code containsKey(key)} is false, this returns an empty collection, not {@code
284   * null}.
285   *
286   * <p>Changes to the returned collection will update the underlying multimap, and vice versa.
287   */
288  Collection<V> get(@NullableDecl K key);
289
290  /**
291   * Returns a view collection of all <i>distinct</i> keys contained in this multimap. Note that the
292   * key set contains a key if and only if this multimap maps that key to at least one value.
293   *
294   * <p>Changes to the returned set will update the underlying multimap, and vice versa. However,
295   * <i>adding</i> to the returned set is not possible.
296   */
297  Set<K> keySet();
298
299  /**
300   * Returns a view collection containing the key from each key-value pair in this multimap,
301   * <i>without</i> collapsing duplicates. This collection has the same size as this multimap, and
302   * {@code keys().count(k) == get(k).size()} for all {@code k}.
303   *
304   * <p>Changes to the returned multiset will update the underlying multimap, and vice versa.
305   * However, <i>adding</i> to the returned collection is not possible.
306   */
307  Multiset<K> keys();
308
309  /**
310   * Returns a view collection containing the <i>value</i> from each key-value pair contained in
311   * this multimap, without collapsing duplicates (so {@code values().size() == size()}).
312   *
313   * <p>Changes to the returned collection will update the underlying multimap, and vice versa.
314   * However, <i>adding</i> to the returned collection is not possible.
315   */
316  Collection<V> values();
317
318  /**
319   * Returns a view collection of all key-value pairs contained in this multimap, as {@link Entry}
320   * instances.
321   *
322   * <p>Changes to the returned collection or the entries it contains will update the underlying
323   * multimap, and vice versa. However, <i>adding</i> to the returned collection is not possible.
324   */
325  Collection<Entry<K, V>> entries();
326
327  /**
328   * Returns a view of this multimap as a {@code Map} from each distinct key to the nonempty
329   * collection of that key's associated values. Note that {@code this.asMap().get(k)} is equivalent
330   * to {@code this.get(k)} only when {@code k} is a key contained in the multimap; otherwise it
331   * returns {@code null} as opposed to an empty collection.
332   *
333   * <p>Changes to the returned map or the collections that serve as its values will update the
334   * underlying multimap, and vice versa. The map does not support {@code put} or {@code putAll},
335   * nor do its entries support {@link Entry#setValue setValue}.
336   */
337  Map<K, Collection<V>> asMap();
338
339  // Comparison and hashing
340
341  /**
342   * Compares the specified object with this multimap for equality. Two multimaps are equal when
343   * their map views, as returned by {@link #asMap}, are also equal.
344   *
345   * <p>In general, two multimaps with identical key-value mappings may or may not be equal,
346   * depending on the implementation. For example, two {@link SetMultimap} instances with the same
347   * key-value mappings are equal, but equality of two {@link ListMultimap} instances depends on the
348   * ordering of the values for each key.
349   *
350   * <p>A non-empty {@link SetMultimap} cannot be equal to a non-empty {@link ListMultimap}, since
351   * their {@link #asMap} views contain unequal collections as values. However, any two empty
352   * multimaps are equal, because they both have empty {@link #asMap} views.
353   */
354  @Override
355  boolean equals(@NullableDecl Object obj);
356
357  /**
358   * Returns the hash code for this multimap.
359   *
360   * <p>The hash code of a multimap is defined as the hash code of the map view, as returned by
361   * {@link Multimap#asMap}.
362   *
363   * <p>In general, two multimaps with identical key-value mappings may or may not have the same
364   * hash codes, depending on the implementation. For example, two {@link SetMultimap} instances
365   * with the same key-value mappings will have the same {@code hashCode}, but the {@code hashCode}
366   * of {@link ListMultimap} instances depends on the ordering of the values for each key.
367   */
368  @Override
369  int hashCode();
370}