1 /* 2 * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. Oracle designates this 8 * particular file as subject to the "Classpath" exception as provided 9 * by Oracle in the LICENSE file that accompanied this code. 10 * 11 * This code is distributed in the hope that it will be useful, but WITHOUT 12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 14 * version 2 for more details (a copy is included in the LICENSE file that 15 * accompanied this code). 16 * 17 * You should have received a copy of the GNU General Public License version 18 * 2 along with this work; if not, write to the Free Software Foundation, 19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 20 * 21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 22 * or visit www.oracle.com if you need additional information or have any 23 * questions. 24 */ 25 26 package java.util; 27 28 import java.util.function.BiConsumer; 29 import java.util.function.BiFunction; 30 import java.util.function.Function; 31 32 /** 33 * An object that maps keys to values. A map cannot contain duplicate keys; 34 * each key can map to at most one value. 35 * 36 * <p>This interface takes the place of the <tt>Dictionary</tt> class, which 37 * was a totally abstract class rather than an interface. 38 * 39 * <p>The <tt>Map</tt> interface provides three <i>collection views</i>, which 40 * allow a map's contents to be viewed as a set of keys, collection of values, 41 * or set of key-value mappings. The <i>order</i> of a map is defined as 42 * the order in which the iterators on the map's collection views return their 43 * elements. Some map implementations, like the <tt>TreeMap</tt> class, make 44 * specific guarantees as to their order; others, like the <tt>HashMap</tt> 45 * class, do not. 46 * 47 * <p>Note: great care must be exercised if mutable objects are used as map 48 * keys. The behavior of a map is not specified if the value of an object is 49 * changed in a manner that affects <tt>equals</tt> comparisons while the 50 * object is a key in the map. A special case of this prohibition is that it 51 * is not permissible for a map to contain itself as a key. While it is 52 * permissible for a map to contain itself as a value, extreme caution is 53 * advised: the <tt>equals</tt> and <tt>hashCode</tt> methods are no longer 54 * well defined on such a map. 55 * 56 * <p>All general-purpose map implementation classes should provide two 57 * "standard" constructors: a void (no arguments) constructor which creates an 58 * empty map, and a constructor with a single argument of type <tt>Map</tt>, 59 * which creates a new map with the same key-value mappings as its argument. 60 * In effect, the latter constructor allows the user to copy any map, 61 * producing an equivalent map of the desired class. There is no way to 62 * enforce this recommendation (as interfaces cannot contain constructors) but 63 * all of the general-purpose map implementations in the JDK comply. 64 * 65 * <p>The "destructive" methods contained in this interface, that is, the 66 * methods that modify the map on which they operate, are specified to throw 67 * <tt>UnsupportedOperationException</tt> if this map does not support the 68 * operation. If this is the case, these methods may, but are not required 69 * to, throw an <tt>UnsupportedOperationException</tt> if the invocation would 70 * have no effect on the map. For example, invoking the {@link #putAll(Map)} 71 * method on an unmodifiable map may, but is not required to, throw the 72 * exception if the map whose mappings are to be "superimposed" is empty. 73 * 74 * <p>Some map implementations have restrictions on the keys and values they 75 * may contain. For example, some implementations prohibit null keys and 76 * values, and some have restrictions on the types of their keys. Attempting 77 * to insert an ineligible key or value throws an unchecked exception, 78 * typically <tt>NullPointerException</tt> or <tt>ClassCastException</tt>. 79 * Attempting to query the presence of an ineligible key or value may throw an 80 * exception, or it may simply return false; some implementations will exhibit 81 * the former behavior and some will exhibit the latter. More generally, 82 * attempting an operation on an ineligible key or value whose completion 83 * would not result in the insertion of an ineligible element into the map may 84 * throw an exception or it may succeed, at the option of the implementation. 85 * Such exceptions are marked as "optional" in the specification for this 86 * interface. 87 * 88 * <p>This interface is a member of the 89 * <a href="{@docRoot}/../technotes/guides/collections/index.html"> 90 * Java Collections Framework</a>. 91 * 92 * <p>Many methods in Collections Framework interfaces are defined 93 * in terms of the {@link Object#equals(Object) equals} method. For 94 * example, the specification for the {@link #containsKey(Object) 95 * containsKey(Object key)} method says: "returns <tt>true</tt> if and 96 * only if this map contains a mapping for a key <tt>k</tt> such that 97 * <tt>(key==null ? k==null : key.equals(k))</tt>." This specification should 98 * <i>not</i> be construed to imply that invoking <tt>Map.containsKey</tt> 99 * with a non-null argument <tt>key</tt> will cause <tt>key.equals(k)</tt> to 100 * be invoked for any key <tt>k</tt>. Implementations are free to 101 * implement optimizations whereby the <tt>equals</tt> invocation is avoided, 102 * for example, by first comparing the hash codes of the two keys. (The 103 * {@link Object#hashCode()} specification guarantees that two objects with 104 * unequal hash codes cannot be equal.) More generally, implementations of 105 * the various Collections Framework interfaces are free to take advantage of 106 * the specified behavior of underlying {@link Object} methods wherever the 107 * implementor deems it appropriate. 108 * 109 * @param <K> the type of keys maintained by this map 110 * @param <V> the type of mapped values 111 * 112 * @author Josh Bloch 113 * @see HashMap 114 * @see TreeMap 115 * @see Hashtable 116 * @see SortedMap 117 * @see Collection 118 * @see Set 119 * @since 1.2 120 */ 121 public interface Map<K,V> { 122 // Query Operations 123 124 /** 125 * Returns the number of key-value mappings in this map. If the 126 * map contains more than <tt>Integer.MAX_VALUE</tt> elements, returns 127 * <tt>Integer.MAX_VALUE</tt>. 128 * 129 * @return the number of key-value mappings in this map 130 */ 131 int size(); 132 133 /** 134 * Returns <tt>true</tt> if this map contains no key-value mappings. 135 * 136 * @return <tt>true</tt> if this map contains no key-value mappings 137 */ 138 boolean isEmpty(); 139 140 /** 141 * Returns <tt>true</tt> if this map contains a mapping for the specified 142 * key. More formally, returns <tt>true</tt> if and only if 143 * this map contains a mapping for a key <tt>k</tt> such that 144 * <tt>(key==null ? k==null : key.equals(k))</tt>. (There can be 145 * at most one such mapping.) 146 * 147 * @param key key whose presence in this map is to be tested 148 * @return <tt>true</tt> if this map contains a mapping for the specified 149 * key 150 * @throws ClassCastException if the key is of an inappropriate type for 151 * this map 152 * (<a href="Collection.html#optional-restrictions">optional</a>) 153 * @throws NullPointerException if the specified key is null and this map 154 * does not permit null keys 155 * (<a href="Collection.html#optional-restrictions">optional</a>) 156 */ 157 boolean containsKey(Object key); 158 159 /** 160 * Returns <tt>true</tt> if this map maps one or more keys to the 161 * specified value. More formally, returns <tt>true</tt> if and only if 162 * this map contains at least one mapping to a value <tt>v</tt> such that 163 * <tt>(value==null ? v==null : value.equals(v))</tt>. This operation 164 * will probably require time linear in the map size for most 165 * implementations of the <tt>Map</tt> interface. 166 * 167 * @param value value whose presence in this map is to be tested 168 * @return <tt>true</tt> if this map maps one or more keys to the 169 * specified value 170 * @throws ClassCastException if the value is of an inappropriate type for 171 * this map 172 * (<a href="Collection.html#optional-restrictions">optional</a>) 173 * @throws NullPointerException if the specified value is null and this 174 * map does not permit null values 175 * (<a href="Collection.html#optional-restrictions">optional</a>) 176 */ 177 boolean containsValue(Object value); 178 179 /** 180 * Returns the value to which the specified key is mapped, 181 * or {@code null} if this map contains no mapping for the key. 182 * 183 * <p>More formally, if this map contains a mapping from a key 184 * {@code k} to a value {@code v} such that {@code (key==null ? k==null : 185 * key.equals(k))}, then this method returns {@code v}; otherwise 186 * it returns {@code null}. (There can be at most one such mapping.) 187 * 188 * <p>If this map permits null values, then a return value of 189 * {@code null} does not <i>necessarily</i> indicate that the map 190 * contains no mapping for the key; it's also possible that the map 191 * explicitly maps the key to {@code null}. The {@link #containsKey 192 * containsKey} operation may be used to distinguish these two cases. 193 * 194 * @param key the key whose associated value is to be returned 195 * @return the value to which the specified key is mapped, or 196 * {@code null} if this map contains no mapping for the key 197 * @throws ClassCastException if the key is of an inappropriate type for 198 * this map 199 * (<a href="Collection.html#optional-restrictions">optional</a>) 200 * @throws NullPointerException if the specified key is null and this map 201 * does not permit null keys 202 * (<a href="Collection.html#optional-restrictions">optional</a>) 203 */ 204 V get(Object key); 205 206 // Modification Operations 207 208 /** 209 * Associates the specified value with the specified key in this map 210 * (optional operation). If the map previously contained a mapping for 211 * the key, the old value is replaced by the specified value. (A map 212 * <tt>m</tt> is said to contain a mapping for a key <tt>k</tt> if and only 213 * if {@link #containsKey(Object) m.containsKey(k)} would return 214 * <tt>true</tt>.) 215 * 216 * @param key key with which the specified value is to be associated 217 * @param value value to be associated with the specified key 218 * @return the previous value associated with <tt>key</tt>, or 219 * <tt>null</tt> if there was no mapping for <tt>key</tt>. 220 * (A <tt>null</tt> return can also indicate that the map 221 * previously associated <tt>null</tt> with <tt>key</tt>, 222 * if the implementation supports <tt>null</tt> values.) 223 * @throws UnsupportedOperationException if the <tt>put</tt> operation 224 * is not supported by this map 225 * @throws ClassCastException if the class of the specified key or value 226 * prevents it from being stored in this map 227 * @throws NullPointerException if the specified key or value is null 228 * and this map does not permit null keys or values 229 * @throws IllegalArgumentException if some property of the specified key 230 * or value prevents it from being stored in this map 231 */ 232 V put(K key, V value); 233 234 /** 235 * Removes the mapping for a key from this map if it is present 236 * (optional operation). More formally, if this map contains a mapping 237 * from key <tt>k</tt> to value <tt>v</tt> such that 238 * <code>(key==null ? k==null : key.equals(k))</code>, that mapping 239 * is removed. (The map can contain at most one such mapping.) 240 * 241 * <p>Returns the value to which this map previously associated the key, 242 * or <tt>null</tt> if the map contained no mapping for the key. 243 * 244 * <p>If this map permits null values, then a return value of 245 * <tt>null</tt> does not <i>necessarily</i> indicate that the map 246 * contained no mapping for the key; it's also possible that the map 247 * explicitly mapped the key to <tt>null</tt>. 248 * 249 * <p>The map will not contain a mapping for the specified key once the 250 * call returns. 251 * 252 * @param key key whose mapping is to be removed from the map 253 * @return the previous value associated with <tt>key</tt>, or 254 * <tt>null</tt> if there was no mapping for <tt>key</tt>. 255 * @throws UnsupportedOperationException if the <tt>remove</tt> operation 256 * is not supported by this map 257 * @throws ClassCastException if the key is of an inappropriate type for 258 * this map 259 * (<a href="Collection.html#optional-restrictions">optional</a>) 260 * @throws NullPointerException if the specified key is null and this 261 * map does not permit null keys 262 * (<a href="Collection.html#optional-restrictions">optional</a>) 263 */ 264 V remove(Object key); 265 266 267 // Bulk Operations 268 269 /** 270 * Copies all of the mappings from the specified map to this map 271 * (optional operation). The effect of this call is equivalent to that 272 * of calling {@link #put(Object,Object) put(k, v)} on this map once 273 * for each mapping from key <tt>k</tt> to value <tt>v</tt> in the 274 * specified map. The behavior of this operation is undefined if the 275 * specified map is modified while the operation is in progress. 276 * 277 * @param m mappings to be stored in this map 278 * @throws UnsupportedOperationException if the <tt>putAll</tt> operation 279 * is not supported by this map 280 * @throws ClassCastException if the class of a key or value in the 281 * specified map prevents it from being stored in this map 282 * @throws NullPointerException if the specified map is null, or if 283 * this map does not permit null keys or values, and the 284 * specified map contains null keys or values 285 * @throws IllegalArgumentException if some property of a key or value in 286 * the specified map prevents it from being stored in this map 287 */ 288 void putAll(Map<? extends K, ? extends V> m); 289 290 /** 291 * Removes all of the mappings from this map (optional operation). 292 * The map will be empty after this call returns. 293 * 294 * @throws UnsupportedOperationException if the <tt>clear</tt> operation 295 * is not supported by this map 296 */ 297 void clear(); 298 299 300 // Views 301 302 /** 303 * Returns a {@link Set} view of the keys contained in this map. 304 * The set is backed by the map, so changes to the map are 305 * reflected in the set, and vice-versa. If the map is modified 306 * while an iteration over the set is in progress (except through 307 * the iterator's own <tt>remove</tt> operation), the results of 308 * the iteration are undefined. The set supports element removal, 309 * which removes the corresponding mapping from the map, via the 310 * <tt>Iterator.remove</tt>, <tt>Set.remove</tt>, 311 * <tt>removeAll</tt>, <tt>retainAll</tt>, and <tt>clear</tt> 312 * operations. It does not support the <tt>add</tt> or <tt>addAll</tt> 313 * operations. 314 * 315 * @return a set view of the keys contained in this map 316 */ 317 Set<K> keySet(); 318 319 /** 320 * Returns a {@link Collection} view of the values contained in this map. 321 * The collection is backed by the map, so changes to the map are 322 * reflected in the collection, and vice-versa. If the map is 323 * modified while an iteration over the collection is in progress 324 * (except through the iterator's own <tt>remove</tt> operation), 325 * the results of the iteration are undefined. The collection 326 * supports element removal, which removes the corresponding 327 * mapping from the map, via the <tt>Iterator.remove</tt>, 328 * <tt>Collection.remove</tt>, <tt>removeAll</tt>, 329 * <tt>retainAll</tt> and <tt>clear</tt> operations. It does not 330 * support the <tt>add</tt> or <tt>addAll</tt> operations. 331 * 332 * @return a collection view of the values contained in this map 333 */ 334 Collection<V> values(); 335 336 /** 337 * Returns a {@link Set} view of the mappings contained in this map. 338 * The set is backed by the map, so changes to the map are 339 * reflected in the set, and vice-versa. If the map is modified 340 * while an iteration over the set is in progress (except through 341 * the iterator's own <tt>remove</tt> operation, or through the 342 * <tt>setValue</tt> operation on a map entry returned by the 343 * iterator) the results of the iteration are undefined. The set 344 * supports element removal, which removes the corresponding 345 * mapping from the map, via the <tt>Iterator.remove</tt>, 346 * <tt>Set.remove</tt>, <tt>removeAll</tt>, <tt>retainAll</tt> and 347 * <tt>clear</tt> operations. It does not support the 348 * <tt>add</tt> or <tt>addAll</tt> operations. 349 * 350 * @return a set view of the mappings contained in this map 351 */ 352 Set<Map.Entry<K, V>> entrySet(); 353 354 /** 355 * A map entry (key-value pair). The <tt>Map.entrySet</tt> method returns 356 * a collection-view of the map, whose elements are of this class. The 357 * <i>only</i> way to obtain a reference to a map entry is from the 358 * iterator of this collection-view. These <tt>Map.Entry</tt> objects are 359 * valid <i>only</i> for the duration of the iteration; more formally, 360 * the behavior of a map entry is undefined if the backing map has been 361 * modified after the entry was returned by the iterator, except through 362 * the <tt>setValue</tt> operation on the map entry. 363 * 364 * @see Map#entrySet() 365 * @since 1.2 366 */ 367 interface Entry<K,V> { 368 /** 369 * Returns the key corresponding to this entry. 370 * 371 * @return the key corresponding to this entry 372 * @throws IllegalStateException implementations may, but are not 373 * required to, throw this exception if the entry has been 374 * removed from the backing map. 375 */ 376 K getKey(); 377 378 /** 379 * Returns the value corresponding to this entry. If the mapping 380 * has been removed from the backing map (by the iterator's 381 * <tt>remove</tt> operation), the results of this call are undefined. 382 * 383 * @return the value corresponding to this entry 384 * @throws IllegalStateException implementations may, but are not 385 * required to, throw this exception if the entry has been 386 * removed from the backing map. 387 */ 388 V getValue(); 389 390 /** 391 * Replaces the value corresponding to this entry with the specified 392 * value (optional operation). (Writes through to the map.) The 393 * behavior of this call is undefined if the mapping has already been 394 * removed from the map (by the iterator's <tt>remove</tt> operation). 395 * 396 * @param value new value to be stored in this entry 397 * @return old value corresponding to the entry 398 * @throws UnsupportedOperationException if the <tt>put</tt> operation 399 * is not supported by the backing map 400 * @throws ClassCastException if the class of the specified value 401 * prevents it from being stored in the backing map 402 * @throws NullPointerException if the backing map does not permit 403 * null values, and the specified value is null 404 * @throws IllegalArgumentException if some property of this value 405 * prevents it from being stored in the backing map 406 * @throws IllegalStateException implementations may, but are not 407 * required to, throw this exception if the entry has been 408 * removed from the backing map. 409 */ 410 V setValue(V value); 411 412 /** 413 * Compares the specified object with this entry for equality. 414 * Returns <tt>true</tt> if the given object is also a map entry and 415 * the two entries represent the same mapping. More formally, two 416 * entries <tt>e1</tt> and <tt>e2</tt> represent the same mapping 417 * if<pre> 418 * (e1.getKey()==null ? 419 * e2.getKey()==null : e1.getKey().equals(e2.getKey())) && 420 * (e1.getValue()==null ? 421 * e2.getValue()==null : e1.getValue().equals(e2.getValue())) 422 * </pre> 423 * This ensures that the <tt>equals</tt> method works properly across 424 * different implementations of the <tt>Map.Entry</tt> interface. 425 * 426 * @param o object to be compared for equality with this map entry 427 * @return <tt>true</tt> if the specified object is equal to this map 428 * entry 429 */ 430 boolean equals(Object o); 431 432 /** 433 * Returns the hash code value for this map entry. The hash code 434 * of a map entry <tt>e</tt> is defined to be: <pre> 435 * (e.getKey()==null ? 0 : e.getKey().hashCode()) ^ 436 * (e.getValue()==null ? 0 : e.getValue().hashCode()) 437 * </pre> 438 * This ensures that <tt>e1.equals(e2)</tt> implies that 439 * <tt>e1.hashCode()==e2.hashCode()</tt> for any two Entries 440 * <tt>e1</tt> and <tt>e2</tt>, as required by the general 441 * contract of <tt>Object.hashCode</tt>. 442 * 443 * @return the hash code value for this map entry 444 * @see Object#hashCode() 445 * @see Object#equals(Object) 446 * @see #equals(Object) 447 */ 448 int hashCode(); 449 } 450 451 // Comparison and hashing 452 453 /** 454 * Compares the specified object with this map for equality. Returns 455 * <tt>true</tt> if the given object is also a map and the two maps 456 * represent the same mappings. More formally, two maps <tt>m1</tt> and 457 * <tt>m2</tt> represent the same mappings if 458 * <tt>m1.entrySet().equals(m2.entrySet())</tt>. This ensures that the 459 * <tt>equals</tt> method works properly across different implementations 460 * of the <tt>Map</tt> interface. 461 * 462 * @param o object to be compared for equality with this map 463 * @return <tt>true</tt> if the specified object is equal to this map 464 */ 465 boolean equals(Object o); 466 467 /** 468 * Returns the hash code value for this map. The hash code of a map is 469 * defined to be the sum of the hash codes of each entry in the map's 470 * <tt>entrySet()</tt> view. This ensures that <tt>m1.equals(m2)</tt> 471 * implies that <tt>m1.hashCode()==m2.hashCode()</tt> for any two maps 472 * <tt>m1</tt> and <tt>m2</tt>, as required by the general contract of 473 * {@link Object#hashCode}. 474 * 475 * @return the hash code value for this map 476 * @see Map.Entry#hashCode() 477 * @see Object#equals(Object) 478 * @see #equals(Object) 479 */ 480 int hashCode(); 481 482 // Defaultable methods 483 484 /** 485 * Returns the value to which the specified key is mapped, 486 * or {@code defaultValue} if this map contains no mapping 487 * for the key. 488 * 489 * <p>The default implementation makes no guarantees about synchronization 490 * or atomicity properties of this method. Any implementation providing 491 * atomicity guarantees must override this method and document its 492 * concurrency properties. 493 * 494 * @param key the key whose associated value is to be returned 495 * @return the value to which the specified key is mapped, or 496 * {@code defaultValue} if this map contains no mapping for the key 497 * @throws ClassCastException if the key is of an inappropriate type for 498 * this map 499 * (<a href="Collection.html#optional-restrictions">optional</a>) 500 * @throws NullPointerException if the specified key is null and this map 501 * does not permit null keys 502 * (<a href="Collection.html#optional-restrictions">optional</a>) 503 */ 504 default V getOrDefault(Object key, V defaultValue) { 505 V v; 506 return (((v = get(key)) != null) || containsKey(key)) 507 ? v 508 : defaultValue; 509 } 510 511 /** 512 * Performs the given action on each entry in this map, in the order entries 513 * are returned by an entry set iterator (which may be unspecified), until 514 * all entries have been processed or the action throws an {@code Exception}. 515 * Exceptions thrown by the action are relayed to the caller. 516 * 517 * <p>The default implementation should be overridden by implementations if 518 * they can provide a more performant implementation than an iterator-based 519 * one. 520 * 521 * <p>The default implementation makes no guarantees about synchronization 522 * or atomicity properties of this method. Any implementation providing 523 * atomicity guarantees must override this method and document its 524 * concurrency properties. 525 * 526 * @implSpec The default implementation is equivalent to, for this 527 * {@code map}: 528 * <pre> {@code 529 * for ((Map.Entry<K, V> entry : map.entrySet()) 530 * action.accept(entry.getKey(), entry.getValue()); 531 * }</pre> 532 * 533 * @param action The action to be performed for each entry 534 * @throws NullPointerException if the specified action is null 535 * @throws ConcurrentModificationException if an entry is found to be 536 * removed during iteration 537 * @since 1.8 538 */ 539 default void forEach(BiConsumer<? super K, ? super V> action) { 540 Objects.requireNonNull(action); 541 for (Map.Entry<K, V> entry : entrySet()) { 542 K k; 543 V v; 544 try { 545 k = entry.getKey(); 546 v = entry.getValue(); 547 } catch(IllegalStateException ise) { 548 // this usually means the entry is no longer in the map. 549 throw new ConcurrentModificationException(ise); 550 } 551 action.accept(k, v); 552 } 553 } 554 555 /** 556 * Replaces each entry's value with the result of invoking the given 557 * function on that entry, in the order entries are returned by an entry 558 * set iterator, until all entries have been processed or the function 559 * throws an exception. 560 * 561 * <p>The default implementation makes no guarantees about synchronization 562 * or atomicity properties of this method. Any implementation providing 563 * atomicity guarantees must override this method and document its 564 * concurrency properties. 565 * 566 * @implSpec 567 * <p>The default implementation is equivalent to, for this {@code map}: 568 * <pre> {@code 569 * for ((Map.Entry<K, V> entry : map.entrySet()) 570 * entry.setValue(function.apply(entry.getKey(), entry.getValue())); 571 * }</pre> 572 * 573 * @param function the function to apply to each entry 574 * @throws UnsupportedOperationException if the {@code set} operation 575 * is not supported by this map's entry set iterator. 576 * @throws ClassCastException if the class of a replacement value 577 * prevents it from being stored in this map 578 * @throws NullPointerException if the specified function is null, or the 579 * specified replacement value is null, and this map does not permit null 580 * values 581 * @throws ClassCastException if a replacement value is of an inappropriate 582 * type for this map 583 * (<a href="Collection.html#optional-restrictions">optional</a>) 584 * @throws NullPointerException if function or a replacement value is null, 585 * and this map does not permit null keys or values 586 * (<a href="Collection.html#optional-restrictions">optional</a>) 587 * @throws IllegalArgumentException if some property of a replacement value 588 * prevents it from being stored in this map 589 * (<a href="Collection.html#optional-restrictions">optional</a>) 590 * @throws ConcurrentModificationException if an entry is found to be 591 * removed during iteration 592 * @since 1.8 593 */ 594 default void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) { 595 Objects.requireNonNull(function); 596 for (Map.Entry<K, V> entry : entrySet()) { 597 K k; 598 V v; 599 try { 600 k = entry.getKey(); 601 v = entry.getValue(); 602 } catch(IllegalStateException ise) { 603 // this usually means the entry is no longer in the map. 604 throw new ConcurrentModificationException(ise); 605 } 606 607 // ise thrown from function is not a cme. 608 v = function.apply(k, v); 609 610 try { 611 entry.setValue(v); 612 } catch(IllegalStateException ise) { 613 // this usually means the entry is no longer in the map. 614 throw new ConcurrentModificationException(ise); 615 } 616 } 617 } 618 619 /** 620 * If the specified key is not already associated with a value (or is mapped 621 * to {@code null}) associates it with the given value and returns 622 * {@code null}, else returns the current value. 623 * 624 * <p>The default implementation makes no guarantees about synchronization 625 * or atomicity properties of this method. Any implementation providing 626 * atomicity guarantees must override this method and document its 627 * concurrency properties. 628 * 629 * @implSpec 630 * The default implementation is equivalent to, for this {@code 631 * map}: 632 * 633 * <pre> {@code 634 * if (map.get(key) == null) 635 * return map.put(key, value); 636 * else 637 * return map.get(key); 638 * }</pre> 639 * 640 * @param key key with which the specified value is to be associated 641 * @param value value to be associated with the specified key 642 * @return the previous value associated with the specified key, or 643 * {@code null} if there was no mapping for the key. 644 * (A {@code null} return can also indicate that the map 645 * previously associated {@code null} with the key, 646 * if the implementation supports null values.) 647 * @throws UnsupportedOperationException if the {@code put} operation 648 * is not supported by this map 649 * (<a href="Collection.html#optional-restrictions">optional</a>) 650 * @throws ClassCastException if the key or value is of an inappropriate 651 * type for this map 652 * (<a href="Collection.html#optional-restrictions">optional</a>) 653 * @throws NullPointerException if the specified key or value is null, 654 * and this map does not permit null keys or values 655 * (<a href="Collection.html#optional-restrictions">optional</a>) 656 * @throws IllegalArgumentException if some property of the specified key 657 * or value prevents it from being stored in this map 658 * (<a href="Collection.html#optional-restrictions">optional</a>) 659 * @throws ConcurrentModificationException if a modification of the map is 660 * detected during insertion of the value. 661 * @since 1.8 662 */ 663 default V putIfAbsent(K key, V value) { 664 V v = get(key); 665 if (v == null) { 666 if (put(key, value) != null) { 667 throw new ConcurrentModificationException(); 668 } 669 } 670 671 return v; 672 } 673 674 /** 675 * Removes the entry for the specified key only if it is currently 676 * mapped to the specified value. 677 * 678 * <p>The default implementation makes no guarantees about synchronization 679 * or atomicity properties of this method. Any implementation providing 680 * atomicity guarantees must override this method and document its 681 * concurrency properties. 682 * 683 * @implSpec 684 * The default implementation is equivalent to, for this {@code map}: 685 * 686 * <pre> {@code 687 * if (map.containsKey(key) && Objects.equals(map.get(key), value)) { 688 * map.remove(key); 689 * return true; 690 * } else 691 * return false; 692 * }</pre> 693 * 694 * @param key key with which the specified value is associated 695 * @param value value expected to be associated with the specified key 696 * @return {@code true} if the value was removed 697 * @throws UnsupportedOperationException if the {@code remove} operation 698 * is not supported by this map 699 * (<a href="Collection.html#optional-restrictions">optional</a>) 700 * @throws ClassCastException if the key or value is of an inappropriate 701 * type for this map 702 * (<a href="Collection.html#optional-restrictions">optional</a>) 703 * @throws NullPointerException if the specified key or value is null, 704 * and this map does not permit null keys or values 705 * (<a href="Collection.html#optional-restrictions">optional</a>) 706 * @since 1.8 707 */ 708 default boolean remove(Object key, Object value) { 709 Object curValue = get(key); 710 if (!Objects.equals(curValue, value) || 711 (curValue == null && !containsKey(key))) { 712 return false; 713 } 714 remove(key); 715 return true; 716 } 717 718 /** 719 * Replaces the entry for the specified key only if currently 720 * mapped to the specified value. 721 * 722 * <p>The default implementation makes no guarantees about synchronization 723 * or atomicity properties of this method. Any implementation providing 724 * atomicity guarantees must override this method and document its 725 * concurrency properties. 726 * 727 * @implSpec 728 * The default implementation is equivalent to, for this {@code map}: 729 * 730 * <pre> {@code 731 * if (map.containsKey(key) && Objects.equals(map.get(key), value)) { 732 * map.put(key, newValue); 733 * return true; 734 * } else 735 * return false; 736 * }</pre> 737 * 738 * @param key key with which the specified value is associated 739 * @param oldValue value expected to be associated with the specified key 740 * @param newValue value to be associated with the specified key 741 * @return {@code true} if the value was replaced 742 * @throws UnsupportedOperationException if the {@code put} operation 743 * is not supported by this map 744 * (<a href="Collection.html#optional-restrictions">optional</a>) 745 * @throws ClassCastException if the class of a specified key or value 746 * prevents it from being stored in this map 747 * @throws NullPointerException if a specified key or value is null, 748 * and this map does not permit null keys or values 749 * @throws IllegalArgumentException if some property of a specified key 750 * or value prevents it from being stored in this map 751 * @since 1.8 752 */ 753 default boolean replace(K key, V oldValue, V newValue) { 754 Object curValue = get(key); 755 if (!Objects.equals(curValue, oldValue) || 756 (curValue == null && !containsKey(key))) { 757 return false; 758 } 759 put(key, newValue); 760 return true; 761 } 762 763 /** 764 * Replaces the entry for the specified key only if it is 765 * currently mapped to some value. 766 * 767 * <p>The default implementation makes no guarantees about synchronization 768 * or atomicity properties of this method. Any implementation providing 769 * atomicity guarantees must override this method and document its 770 * concurrency properties. 771 * 772 * @implSpec 773 * The default implementation is equivalent to, for this {@code map}: 774 * 775 * <pre> {@code 776 * if (map.containsKey(key)) { 777 * return map.put(key, value); 778 * } else 779 * return null; 780 * }</pre> 781 * 782 * @param key key with which the specified value is associated 783 * @param value value to be associated with the specified key 784 * @return the previous value associated with the specified key, or 785 * {@code null} if there was no mapping for the key. 786 * (A {@code null} return can also indicate that the map 787 * previously associated {@code null} with the key, 788 * if the implementation supports null values.) 789 * @throws UnsupportedOperationException if the {@code put} operation 790 * is not supported by this map 791 * (<a href="Collection.html#optional-restrictions">optional</a>) 792 * @throws ClassCastException if the class of the specified key or value 793 * prevents it from being stored in this map 794 * (<a href="Collection.html#optional-restrictions">optional</a>) 795 * @throws NullPointerException if the specified key or value is null, 796 * and this map does not permit null keys or values 797 * @throws IllegalArgumentException if some property of the specified key 798 * or value prevents it from being stored in this map 799 * @since 1.8 800 */ 801 default V replace(K key, V value) { 802 return containsKey(key) ? put(key, value) : null; 803 } 804 805 /** 806 * If the specified key is not already associated with a value (or 807 * is mapped to {@code null}), attempts to compute its value using 808 * the given mapping function and enters it into this map unless 809 * {@code null}. 810 * 811 * <p>If the function returns {@code null} no mapping is recorded. If 812 * the function itself throws an (unchecked) exception, the 813 * exception is rethrown, and no mapping is recorded. The most 814 * common usage is to construct a new object serving as an initial 815 * mapped value or memoized result, as in: 816 * 817 * <pre> {@code 818 * map.computeIfAbsent(key, k -> new Value(f(k))); 819 * }</pre> 820 * 821 * <p>The default implementation makes no guarantees about synchronization 822 * or atomicity properties of this method. Any implementation providing 823 * atomicity guarantees must override this method and document its 824 * concurrency properties. In particular, all implementations of 825 * subinterface {@link java.util.concurrent.ConcurrentMap} must document 826 * whether the function is applied once atomically only if the value is not 827 * present. Any class that permits null values must document 828 * whether and how this method distinguishes absence from null mappings. 829 * 830 * @implSpec 831 * The default implementation is equivalent to the following 832 * steps for this {@code map}, then returning the current value or 833 * {@code null} if now absent: 834 * 835 * <pre> {@code 836 * if (map.get(key) == null) { 837 * V newValue = mappingFunction.apply(key); 838 * if (newValue != null) 839 * map.putIfAbsent(key, newValue); 840 * } 841 * }</pre> 842 * 843 * @param key key with which the specified value is to be associated 844 * @param mappingFunction the function to compute a value 845 * @return the current (existing or computed) value associated with 846 * the specified key, or null if the computed value is null 847 * @throws NullPointerException if the specified key is null and 848 * this map does not support null keys, or the 849 * mappingFunction is null 850 * @throws UnsupportedOperationException if the {@code put} operation 851 * is not supported by this map 852 * (<a href="Collection.html#optional-restrictions">optional</a>) 853 * @throws ClassCastException if the class of the specified key or value 854 * prevents it from being stored in this map 855 * (<a href="Collection.html#optional-restrictions">optional</a>) 856 * @since 1.8 857 */ 858 default V computeIfAbsent(K key, 859 Function<? super K, ? extends V> mappingFunction) { 860 V v, newValue; 861 return ((v = get(key)) == null && 862 (newValue = mappingFunction.apply(key)) != null && 863 (v = putIfAbsent(key, newValue)) == null) ? newValue : v; 864 } 865 866 /** 867 * If the value for the specified key is present and non-null, attempts to 868 * compute a new mapping given the key and its current mapped value. 869 * 870 * <p>If the function returns {@code null}, the mapping is removed. If the 871 * function itself throws an (unchecked) exception, the exception is 872 * rethrown, and the current mapping is left unchanged. 873 * 874 * <p>The default implementation makes no guarantees about synchronization 875 * or atomicity properties of this method. Any implementation providing 876 * atomicity guarantees must override this method and document its 877 * concurrency properties. In particular, all implementations of 878 * subinterface {@link java.util.concurrent.ConcurrentMap} must document 879 * whether the function is applied once atomically only if the value is not 880 * present. Any class that permits null values must document 881 * whether and how this method distinguishes absence from null mappings. 882 * 883 * @implSpec 884 * The default implementation is equivalent to performing the 885 * following steps for this {@code map}, then returning the 886 * current value or {@code null} if now absent: 887 * 888 * <pre> {@code 889 * if (map.get(key) != null) { 890 * V oldValue = map.get(key); 891 * V newValue = remappingFunction.apply(key, oldValue); 892 * if (newValue != null) 893 * map.replace(key, oldValue, newValue); 894 * else 895 * map.remove(key, oldValue); 896 * } 897 * }</pre> 898 * 899 * In concurrent contexts, the default implementation may retry 900 * these steps when multiple threads attempt updates. 901 * 902 * @param key key with which the specified value is to be associated 903 * @param remappingFunction the function to compute a value 904 * @return the new value associated with the specified key, or null if none 905 * @throws NullPointerException if the specified key is null and 906 * this map does not support null keys, or the 907 * remappingFunction is null 908 * @throws UnsupportedOperationException if the {@code put} operation 909 * is not supported by this map 910 * (<a href="Collection.html#optional-restrictions">optional</a>) 911 * @throws ClassCastException if the class of the specified key or value 912 * prevents it from being stored in this map 913 * (<a href="Collection.html#optional-restrictions">optional</a>) 914 * @since 1.8 915 */ 916 default V computeIfPresent(K key, 917 BiFunction<? super K, ? super V, ? extends V> remappingFunction) { 918 V oldValue; 919 while ((oldValue = get(key)) != null) { 920 V newValue = remappingFunction.apply(key, oldValue); 921 if (newValue != null) { 922 if (replace(key, oldValue, newValue)) 923 return newValue; 924 } else if (remove(key, oldValue)) 925 return null; 926 } 927 return oldValue; 928 } 929 930 /** 931 * Attempts to compute a mapping for the specified key and its 932 * current mapped value (or {@code null} if there is no current 933 * mapping). For example, to either create or append a {@code 934 * String msg} to a value mapping: 935 * 936 * <pre> {@code 937 * map.compute(key, (k, v) -> (v == null) ? msg : v.concat(msg))}</pre> 938 * (Method {@link #merge merge()} is often simpler to use for such purposes.) 939 * 940 * <p>If the function returns {@code null}, the mapping is removed (or 941 * remains absent if initially absent). If the function itself throws an 942 * (unchecked) exception, the exception is rethrown, and the current mapping 943 * is left unchanged. 944 * 945 * <p>The default implementation makes no guarantees about synchronization 946 * or atomicity properties of this method. Any implementation providing 947 * atomicity guarantees must override this method and document its 948 * concurrency properties. In particular, all implementations of 949 * subinterface {@link java.util.concurrent.ConcurrentMap} must document 950 * whether the function is applied once atomically only if the value is not 951 * present. Any class that permits null values must document 952 * whether and how this method distinguishes absence from null mappings. 953 * 954 * @implSpec 955 * The default implementation is equivalent to performing the following 956 * steps for this {@code map}, then returning the current value or 957 * {@code null} if absent: 958 * 959 * <pre> {@code 960 * V oldValue = map.get(key); 961 * V newValue = remappingFunction.apply(key, oldValue); 962 * if (oldValue != null ) { 963 * if (newValue != null) 964 * map.replace(key, oldValue, newValue); 965 * else 966 * map.remove(key, oldValue); 967 * } else { 968 * if (newValue != null) 969 * map.putIfAbsent(key, newValue); 970 * else 971 * return null; 972 * } 973 * }</pre> 974 * 975 * In concurrent contexts, the default implementation may retry 976 * these steps when multiple threads attempt updates. 977 * 978 * @param key key with which the specified value is to be associated 979 * @param remappingFunction the function to compute a value 980 * @return the new value associated with the specified key, or null if none 981 * @throws NullPointerException if the specified key is null and 982 * this map does not support null keys, or the 983 * remappingFunction is null 984 * @throws UnsupportedOperationException if the {@code put} operation 985 * is not supported by this map 986 * (<a href="Collection.html#optional-restrictions">optional</a>) 987 * @throws ClassCastException if the class of the specified key or value 988 * prevents it from being stored in this map 989 * (<a href="Collection.html#optional-restrictions">optional</a>) 990 * @since 1.8 991 */ 992 default V compute(K key, 993 BiFunction<? super K, ? super V, ? extends V> remappingFunction) { 994 V oldValue = get(key); 995 for (;;) { 996 V newValue = remappingFunction.apply(key, oldValue); 997 if (newValue == null) { 998 // delete mapping 999 if(oldValue != null || containsKey(key)) { 1000 // something to remove 1001 if (remove(key, oldValue)) { 1002 // removed the old value as expected 1003 return null; 1004 } 1005 1006 // some other value replaced old value. try again. 1007 oldValue = get(key); 1008 } else { 1009 // nothing to do. Leave things as they were. 1010 return null; 1011 } 1012 } else { 1013 // add or replace old mapping 1014 if (oldValue != null) { 1015 // replace 1016 if (replace(key, oldValue, newValue)) { 1017 // replaced as expected. 1018 return newValue; 1019 } 1020 1021 // some other value replaced old value. try again. 1022 oldValue = get(key); 1023 } else { 1024 // add (replace if oldValue was null) 1025 if ((oldValue = putIfAbsent(key, newValue)) == null) { 1026 // replaced 1027 return newValue; 1028 } 1029 1030 // some other value replaced old value. try again. 1031 } 1032 } 1033 } 1034 } 1035 1036 /** 1037 * If the specified key is not already associated with a value or is 1038 * associated with null, associates it with the given value. 1039 * Otherwise, replaces the value with the results of the given 1040 * remapping function, or removes if the result is {@code null}. This 1041 * method may be of use when combining multiple mapped values for a key. 1042 * For example, to either create or append a {@code String msg} to a 1043 * value mapping: 1044 * 1045 * <pre> {@code 1046 * map.merge(key, msg, String::concat) 1047 * }</pre> 1048 * 1049 * <p>If the function returns {@code null}, the mapping is removed (or 1050 * remains absent if initially absent). If the function itself throws an 1051 * (unchecked) exception, the exception is rethrown, and the current mapping 1052 * is left unchanged. 1053 * 1054 * <p>The default implementation makes no guarantees about synchronization 1055 * or atomicity properties of this method. Any implementation providing 1056 * atomicity guarantees must override this method and document its 1057 * concurrency properties. In particular, all implementations of 1058 * subinterface {@link java.util.concurrent.ConcurrentMap} must document 1059 * whether the function is applied once atomically only if the value is not 1060 * present. Any class that permits null values must document 1061 * whether and how this method distinguishes absence from null mappings. 1062 * 1063 * @implSpec 1064 * The default implementation is equivalent to performing the 1065 * following steps for this {@code map}, then returning the 1066 * current value or {@code null} if absent: 1067 * 1068 * <pre> {@code 1069 * V oldValue = map.get(key); 1070 * V newValue = (oldValue == null) ? value : 1071 * remappingFunction.apply(oldValue, value); 1072 * if (newValue == null) 1073 * map.remove(key, oldValue); 1074 * else if (oldValue == null) 1075 * map.putIfAbsent(key, newValue); 1076 * else 1077 * map.replace(key, oldValue, newValue); 1078 * }</pre> 1079 * 1080 * In concurrent contexts, the default implementation may retry 1081 * these steps when multiple threads attempt updates. 1082 * 1083 * @param key key with which the specified value is to be associated 1084 * @param value the value to use if absent 1085 * @param remappingFunction the function to recompute a value if present 1086 * @return the new value associated with the specified key, or null if none 1087 * @throws UnsupportedOperationException if the {@code put} operation 1088 * is not supported by this map 1089 * (<a href="Collection.html#optional-restrictions">optional</a>) 1090 * @throws ClassCastException if the class of the specified key or value 1091 * prevents it from being stored in this map 1092 * (<a href="Collection.html#optional-restrictions">optional</a>) 1093 * @throws NullPointerException if the specified key is null and 1094 * this map does not support null keys, or the 1095 * remappingFunction is null 1096 * @since 1.8 1097 */ 1098 default V merge(K key, V value, 1099 BiFunction<? super V, ? super V, ? extends V> remappingFunction) { 1100 V oldValue = get(key); 1101 for (;;) { 1102 if (oldValue != null) { 1103 V newValue = remappingFunction.apply(oldValue, value); 1104 if (newValue != null) { 1105 if (replace(key, oldValue, newValue)) 1106 return newValue; 1107 } else if (remove(key, oldValue)) { 1108 return null; 1109 } 1110 oldValue = get(key); 1111 } else { 1112 if (value == null) { 1113 return null; 1114 } 1115 1116 if ((oldValue = putIfAbsent(key, value)) == null) { 1117 return value; 1118 } 1119 } 1120 } 1121 } 1122 }