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