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