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