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; 020 021import java.util.Collection; 022import java.util.List; 023import java.util.Map; 024import java.util.Set; 025 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). The 111 * recommended subinterfaces provide a much stronger guarantee. 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 * "http://code.google.com/p/guava-libraries/wiki/NewCollectionTypesExplained#Multimap"> 157 * {@code Multimap}</a>. 158 * 159 * @author Jared Levy 160 * @since 2.0 (imported from Google Collections Library) 161 */ 162@GwtCompatible 163public interface Multimap<K, V> { 164 // Query Operations 165 166 /** Returns the number of key-value pairs in the multimap. */ 167 int size(); 168 169 /** Returns {@code true} if the multimap contains no key-value pairs. */ 170 boolean isEmpty(); 171 172 /** 173 * Returns {@code true} if the multimap contains any values for the specified 174 * key. 175 * 176 * @param key key to search for in multimap 177 */ 178 boolean containsKey(@Nullable Object key); 179 180 /** 181 * Returns {@code true} if the multimap contains the specified value for any 182 * key. 183 * 184 * @param value value to search for in multimap 185 */ 186 boolean containsValue(@Nullable Object value); 187 188 /** 189 * Returns {@code true} if the multimap contains the specified key-value pair. 190 * 191 * @param key key to search for in multimap 192 * @param value value to search for in multimap 193 */ 194 boolean containsEntry(@Nullable Object key, @Nullable Object value); 195 196 // Modification Operations 197 198 /** 199 * Stores a key-value pair in the multimap. 200 * 201 * <p>Some multimap implementations allow duplicate key-value pairs, in which 202 * case {@code put} always adds a new key-value pair and increases the 203 * multimap size by 1. Other implementations prohibit duplicates, and storing 204 * a key-value pair that's already in the multimap has no effect. 205 * 206 * @param key key to store in the multimap 207 * @param value value to store in the multimap 208 * @return {@code true} if the method increased the size of the multimap, or 209 * {@code false} if the multimap already contained the key-value pair and 210 * doesn't allow duplicates 211 */ 212 boolean put(@Nullable K key, @Nullable V value); 213 214 /** 215 * Removes a single key-value pair from the multimap. 216 * 217 * @param key key of entry to remove from the multimap 218 * @param value value of entry to remove the multimap 219 * @return {@code true} if the multimap changed 220 */ 221 boolean remove(@Nullable Object key, @Nullable Object value); 222 223 // Bulk Operations 224 225 /** 226 * Stores key-value pairs in this multimap with one key and multiple values. 227 * 228 * <p>This is equivalent to <pre> {@code 229 * 230 * for (V value : values) { 231 * put(key, value); 232 * } }</pre> 233 * 234 * <p>In particular, this is a no-op if {@code values} is empty. 235 * 236 * @param key key to store in the multimap 237 * @param values values to store in the multimap 238 * @return {@code true} if the multimap changed 239 */ 240 boolean putAll(@Nullable K key, Iterable<? extends V> values); 241 242 /** 243 * Copies all of another multimap's key-value pairs into this multimap. The 244 * order in which the mappings are added is determined by 245 * {@code multimap.entries()}. 246 * 247 * @param multimap mappings to store in this multimap 248 * @return {@code true} if the multimap changed 249 */ 250 boolean putAll(Multimap<? extends K, ? extends V> multimap); 251 252 /** 253 * Stores a collection of values with the same key, replacing any existing 254 * values for that key. 255 * 256 * <p>If {@code values} is empty, this is equivalent to 257 * {@link #removeAll(Object) removeAll(key)}. 258 * 259 * @param key key to store in the multimap 260 * @param values values to store in the multimap 261 * @return the collection of replaced values, or an empty collection if no 262 * values were previously associated with the key. The collection 263 * <i>may</i> be modifiable, but updating it will have no effect on the 264 * multimap. 265 */ 266 Collection<V> replaceValues(@Nullable K key, Iterable<? extends V> values); 267 268 /** 269 * Removes all values associated with a given key. 270 * 271 * <p>Once this method returns, {@code key} will not be mapped to any values, 272 * so it will not appear in {@link #keySet()}, {@link #asMap()}, or any other 273 * views. 274 * 275 * @param key key of entries to remove from the multimap 276 * @return the collection of removed values, or an empty collection if no 277 * values were associated with the provided key. The collection 278 * <i>may</i> be modifiable, but updating it will have no effect on the 279 * multimap. 280 */ 281 Collection<V> removeAll(@Nullable Object key); 282 283 /** 284 * Removes all key-value pairs from the multimap. 285 */ 286 void clear(); 287 288 // Views 289 290 /** 291 * Returns a collection view containing the values associated with {@code key} 292 * in this multimap, if any. Note that even when ({@code containsKey(key)} is 293 * false, {@code get(key)} still returns an empty collection, not {@code 294 * null}. 295 * 296 * <p>Changes to the returned collection will update the underlying multimap, 297 * and vice versa. 298 * 299 * @param key key to search for in multimap 300 * @return a view collection containing the zero or more values that the key 301 * maps to 302 */ 303 Collection<V> get(@Nullable K key); 304 305 /** 306 * Returns the set of all keys, each appearing once in the returned set. 307 * Changes to the returned set will update the underlying multimap, and vice 308 * versa. 309 * 310 * <p>Note that the key set contains a key if and only if this multimap maps 311 * that key to at least one value. 312 * 313 * @return the collection of distinct keys 314 */ 315 Set<K> keySet(); 316 317 /** 318 * Returns a collection, which may contain duplicates, of all keys. The number 319 * of times of key appears in the returned multiset equals the number of 320 * mappings the key has in the multimap. Changes to the returned multiset will 321 * update the underlying multimap, and vice versa. 322 * 323 * @return a multiset with keys corresponding to the distinct keys of the 324 * multimap and frequencies corresponding to the number of values that 325 * each key maps to 326 */ 327 Multiset<K> keys(); 328 329 /** 330 * Returns a collection of all values in the multimap. Changes to the returned 331 * collection will update the underlying multimap, and vice versa. 332 * 333 * @return collection of values, which may include the same value multiple 334 * times if it occurs in multiple mappings 335 */ 336 Collection<V> values(); 337 338 /** 339 * Returns a collection of all key-value pairs. Changes to the returned 340 * collection will update the underlying multimap, and vice versa. The entries 341 * collection does not support the {@code add} or {@code addAll} operations. 342 * 343 * @return collection of map entries consisting of key-value pairs 344 */ 345 Collection<Map.Entry<K, V>> entries(); 346 347 /** 348 * Returns a map view that associates each key with the corresponding values 349 * in the multimap. Changes to the returned map, such as element removal, will 350 * update the underlying multimap. The map does not support {@code setValue()} 351 * on its entries, {@code put}, or {@code putAll}. 352 * 353 * <p>When passed a key that is present in the map, {@code 354 * asMap().get(Object)} has the same behavior as {@link #get}, returning a 355 * live collection. When passed a key that is not present, however, {@code 356 * asMap().get(Object)} returns {@code null} instead of an empty collection. 357 * 358 * @return a map view from a key to its collection of values 359 */ 360 Map<K, Collection<V>> asMap(); 361 362 // Comparison and hashing 363 364 /** 365 * Compares the specified object with this multimap for equality. Two 366 * multimaps are equal when their map views, as returned by {@link #asMap}, 367 * are also equal. 368 * 369 * <p>In general, two multimaps with identical key-value mappings may or may 370 * not be equal, depending on the implementation. For example, two 371 * {@link SetMultimap} instances with the same key-value mappings are equal, 372 * but equality of two {@link ListMultimap} instances depends on the ordering 373 * of the values for each key. 374 * 375 * <p>A non-empty {@link SetMultimap} cannot be equal to a non-empty 376 * {@link ListMultimap}, since their {@link #asMap} views contain unequal 377 * collections as values. However, any two empty multimaps are equal, because 378 * they both have empty {@link #asMap} views. 379 */ 380 @Override 381 boolean equals(@Nullable Object obj); 382 383 /** 384 * Returns the hash code for this multimap. 385 * 386 * <p>The hash code of a multimap is defined as the hash code of the map view, 387 * as returned by {@link Multimap#asMap}. 388 */ 389 @Override 390 int hashCode(); 391}