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