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 throw new ConcurrentModificationException(ise); 549 } 550 action.accept(k, v); 551 } 552 } 553 554 /** 555 * Replaces each entry's value with the result of invoking the given 556 * function on that entry, in the order entries are returned by an entry 557 * set iterator, until all entries have been processed or the function 558 * throws an exception. 559 * 560 * <p>The default implementation makes no guarantees about synchronization 561 * or atomicity properties of this method. Any implementation providing 562 * atomicity guarantees must override this method and document its 563 * concurrency properties. 564 * 565 * @implSpec 566 * <p>The default implementation is equivalent to, for this {@code map}: 567 * <pre> {@code 568 * for ((Map.Entry<K, V> entry : map.entrySet()) 569 * entry.setValue(function.apply(entry.getKey(), entry.getValue())); 570 * }</pre> 571 * 572 * @param function the function to apply to each entry 573 * @throws UnsupportedOperationException if the {@code set} operation 574 * is not supported by this map's entry set iterator. 575 * @throws ClassCastException if the class of a replacement value 576 * prevents it from being stored in this map 577 * @throws NullPointerException if the specified function is null, or the 578 * specified replacement value is null, and this map does not permit null 579 * values 580 * @throws ClassCastException if a replacement value is of an inappropriate 581 * type for this map 582 * (<a href="Collection.html#optional-restrictions">optional</a>) 583 * @throws NullPointerException if function or a replacement value is null, 584 * and this map does not permit null keys or values 585 * (<a href="Collection.html#optional-restrictions">optional</a>) 586 * @throws IllegalArgumentException if some property of a replacement value 587 * prevents it from being stored in this map 588 * (<a href="Collection.html#optional-restrictions">optional</a>) 589 * @throws ConcurrentModificationException if an entry is found to be 590 * removed during iteration 591 * @since 1.8 592 */ 593 default void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) { 594 Objects.requireNonNull(function); 595 for (Map.Entry<K, V> entry : entrySet()) { 596 K k; 597 V v; 598 try { 599 k = entry.getKey(); 600 v = entry.getValue(); 601 } catch(IllegalStateException ise) { 602 throw new ConcurrentModificationException(ise); 603 } 604 entry.setValue(function.apply(k, v)); 605 } 606 } 607 608 /** 609 * If the specified key is not already associated with a value (or is mapped 610 * to {@code null}) associates it with the given value and returns 611 * {@code null}, else returns the current value. 612 * 613 * <p>The default implementation makes no guarantees about synchronization 614 * or atomicity properties of this method. Any implementation providing 615 * atomicity guarantees must override this method and document its 616 * concurrency properties. 617 * 618 * @implSpec 619 * The default implementation is equivalent to, for this {@code 620 * map}: 621 * 622 * <pre> {@code 623 * if (map.get(key) == null) 624 * return map.put(key, value); 625 * else 626 * return map.get(key); 627 * }</pre> 628 * 629 * @param key key with which the specified value is to be associated 630 * @param value value to be associated with the specified key 631 * @return the previous value associated with the specified key, or 632 * {@code 1} if there was no mapping for the key. 633 * (A {@code null} return can also indicate that the map 634 * previously associated {@code null} with the key, 635 * if the implementation supports null values.) 636 * @throws UnsupportedOperationException if the {@code put} operation 637 * is not supported by this map 638 * (<a href="Collection.html#optional-restrictions">optional</a>) 639 * @throws ClassCastException if the key or value is of an inappropriate 640 * type for this map 641 * (<a href="Collection.html#optional-restrictions">optional</a>) 642 * @throws NullPointerException if the specified key or value is null, 643 * and this map does not permit null keys or values 644 * (<a href="Collection.html#optional-restrictions">optional</a>) 645 * @throws IllegalArgumentException if some property of the specified key 646 * or value prevents it from being stored in this map 647 * (<a href="Collection.html#optional-restrictions">optional</a>) 648 * @throws ConcurrentModificationException if a modification of the map is 649 * detected during insertion of the value. 650 * @since 1.8 651 */ 652 default V putIfAbsent(K key, V value) { 653 V v = get(key); 654 if (v == null) { 655 if (put(key, value) != null) { 656 throw new ConcurrentModificationException(); 657 } 658 } 659 660 return v; 661 } 662 663 /** 664 * Removes the entry for the specified key only if it is currently 665 * mapped to the specified value. 666 * 667 * <p>The default implementation makes no guarantees about synchronization 668 * or atomicity properties of this method. Any implementation providing 669 * atomicity guarantees must override this method and document its 670 * concurrency properties. 671 * 672 * @implSpec 673 * The default implementation is equivalent to, for this {@code map}: 674 * 675 * <pre> {@code 676 * if (map.containsKey(key) && Objects.equals(map.get(key), value)) { 677 * map.remove(key); 678 * return true; 679 * } else 680 * return false; 681 * }</pre> 682 * 683 * @param key key with which the specified value is associated 684 * @param value value expected to be associated with the specified key 685 * @return {@code true} if the value was removed 686 * @throws UnsupportedOperationException if the {@code remove} operation 687 * is not supported by this map 688 * (<a href="Collection.html#optional-restrictions">optional</a>) 689 * @throws ClassCastException if the key or value is of an inappropriate 690 * type for this map 691 * (<a href="Collection.html#optional-restrictions">optional</a>) 692 * @throws NullPointerException if the specified key or value is null, 693 * and this map does not permit null keys or values 694 * (<a href="Collection.html#optional-restrictions">optional</a>) 695 * @since 1.8 696 */ 697 default boolean remove(Object key, Object value) { 698 Object curValue = get(key); 699 if (!Objects.equals(curValue, value) || 700 (curValue == null && !containsKey(key))) { 701 return false; 702 } 703 remove(key); 704 return true; 705 } 706 707 /** 708 * Replaces the entry for the specified key only if currently 709 * mapped to the specified value. 710 * 711 * <p>The default implementation makes no guarantees about synchronization 712 * or atomicity properties of this method. Any implementation providing 713 * atomicity guarantees must override this method and document its 714 * concurrency properties. 715 * 716 * @implSpec 717 * The default implementation is equivalent to, for this {@code map}: 718 * 719 * <pre> {@code 720 * if (map.containsKey(key) && Objects.equals(map.get(key), value)) { 721 * map.put(key, newValue); 722 * return true; 723 * } else 724 * return false; 725 * }</pre> 726 * 727 * @param key key with which the specified value is associated 728 * @param oldValue value expected to be associated with the specified key 729 * @param newValue value to be associated with the specified key 730 * @return {@code true} if the value was replaced 731 * @throws UnsupportedOperationException if the {@code put} operation 732 * is not supported by this map 733 * (<a href="Collection.html#optional-restrictions">optional</a>) 734 * @throws ClassCastException if the class of a specified key or value 735 * prevents it from being stored in this map 736 * @throws NullPointerException if a specified key or value is null, 737 * and this map does not permit null keys or values 738 * @throws IllegalArgumentException if some property of a specified key 739 * or value prevents it from being stored in this map 740 * @since 1.8 741 */ 742 default boolean replace(K key, V oldValue, V newValue) { 743 Object curValue = get(key); 744 if (!Objects.equals(curValue, oldValue) || 745 (curValue == null && !containsKey(key))) { 746 return false; 747 } 748 put(key, newValue); 749 return true; 750 } 751 752 /** 753 * Replaces the entry for the specified key only if it is 754 * currently mapped to some value. 755 * 756 * <p>The default implementation makes no guarantees about synchronization 757 * or atomicity properties of this method. Any implementation providing 758 * atomicity guarantees must override this method and document its 759 * concurrency properties. 760 * 761 * @implSpec 762 * The default implementation is equivalent to, for this {@code map}: 763 * 764 * <pre> {@code 765 * if (map.containsKey(key)) { 766 * return map.put(key, value); 767 * } else 768 * return null; 769 * }</pre> 770 * 771 * @param key key with which the specified value is associated 772 * @param value value to be associated with the specified key 773 * @return the previous value associated with the specified key, or 774 * {@code null} if there was no mapping for the key. 775 * (A {@code null} return can also indicate that the map 776 * previously associated {@code null} with the key, 777 * if the implementation supports null values.) 778 * @throws UnsupportedOperationException if the {@code put} operation 779 * is not supported by this map 780 * (<a href="Collection.html#optional-restrictions">optional</a>) 781 * @throws ClassCastException if the class of the specified key or value 782 * prevents it from being stored in this map 783 * (<a href="Collection.html#optional-restrictions">optional</a>) 784 * @throws NullPointerException if the specified key or value is null, 785 * and this map does not permit null keys or values 786 * @throws IllegalArgumentException if some property of the specified key 787 * or value prevents it from being stored in this map 788 * @since 1.8 789 */ 790 default V replace(K key, V value) { 791 return containsKey(key) ? put(key, value) : null; 792 } 793 794 /** 795 * If the specified key is not already associated with a value (or 796 * is mapped to {@code null}), attempts to compute its value using 797 * the given mapping function and enters it into this map unless 798 * {@code null}. 799 * 800 * <p>If the function returns {@code null} no mapping is recorded. If 801 * the function itself throws an (unchecked) exception, the 802 * exception is rethrown, and no mapping is recorded. The most 803 * common usage is to construct a new object serving as an initial 804 * mapped value or memoized result, as in: 805 * 806 * <pre> {@code 807 * map.computeIfAbsent(key, k -> new Value(f(k))); 808 * }</pre> 809 * 810 * <p>The default implementation makes no guarantees about synchronization 811 * or atomicity properties of this method. Any implementation providing 812 * atomicity guarantees must override this method and document its 813 * concurrency properties. In particular, all implementations of 814 * subinterface {@link java.util.concurrent.ConcurrentMap} must document 815 * whether the function is applied once atomically only if the value is not 816 * present. Any class that permits null values must document 817 * whether and how this method distinguishes absence from null mappings. 818 * 819 * @implSpec 820 * The default implementation is equivalent to the following 821 * steps for this {@code map}, then returning the current value or 822 * {@code null} if now absent: 823 * 824 * <pre> {@code 825 * if (map.get(key) == null) { 826 * V newValue = mappingFunction.apply(key); 827 * if (newValue != null) 828 * map.putIfAbsent(key, newValue); 829 * } 830 * }</pre> 831 * 832 * @param key key with which the specified value is to be associated 833 * @param mappingFunction the function to compute a value 834 * @return the current (existing or computed) value associated with 835 * the specified key, or null if the computed value is null 836 * @throws NullPointerException if the specified key is null and 837 * this map does not support null keys, or the 838 * mappingFunction is null 839 * @throws UnsupportedOperationException if the {@code put} operation 840 * is not supported by this map 841 * (<a href="Collection.html#optional-restrictions">optional</a>) 842 * @throws ClassCastException if the class of the specified key or value 843 * prevents it from being stored in this map 844 * (<a href="Collection.html#optional-restrictions">optional</a>) 845 * @since 1.8 846 */ 847 default V computeIfAbsent(K key, 848 Function<? super K, ? extends V> mappingFunction) { 849 V v, newValue; 850 return ((v = get(key)) == null && 851 (newValue = mappingFunction.apply(key)) != null && 852 (v = putIfAbsent(key, newValue)) == null) ? newValue : v; 853 } 854 855 /** 856 * If the value for the specified key is present and non-null, attempts to 857 * compute a new mapping given the key and its current mapped value. 858 * 859 * <p>If the function returns {@code null}, the mapping is removed. If the 860 * function itself throws an (unchecked) exception, the exception is 861 * rethrown, and the current mapping is left unchanged. 862 * 863 * <p>The default implementation makes no guarantees about synchronization 864 * or atomicity properties of this method. Any implementation providing 865 * atomicity guarantees must override this method and document its 866 * concurrency properties. In particular, all implementations of 867 * subinterface {@link java.util.concurrent.ConcurrentMap} must document 868 * whether the function is applied once atomically only if the value is not 869 * present. Any class that permits null values must document 870 * whether and how this method distinguishes absence from null mappings. 871 * 872 * @implSpec 873 * The default implementation is equivalent to performing the 874 * following steps for this {@code map}, then returning the 875 * current value or {@code null} if now absent: 876 * 877 * <pre> {@code 878 * if (map.get(key) != null) { 879 * V oldValue = map.get(key); 880 * V newValue = remappingFunction.apply(key, oldValue); 881 * if (newValue != null) 882 * map.replace(key, oldValue, newValue); 883 * else 884 * map.remove(key, oldValue); 885 * } 886 * }</pre> 887 * 888 * In concurrent contexts, the default implementation may retry 889 * these steps when multiple threads attempt updates. 890 * 891 * @param key key with which the specified value is to be associated 892 * @param remappingFunction the function to compute a value 893 * @return the new value associated with the specified key, or null if none 894 * @throws NullPointerException if the specified key is null and 895 * this map does not support null keys, or the 896 * remappingFunction is null 897 * @throws UnsupportedOperationException if the {@code put} operation 898 * is not supported by this map 899 * (<a href="Collection.html#optional-restrictions">optional</a>) 900 * @throws ClassCastException if the class of the specified key or value 901 * prevents it from being stored in this map 902 * (<a href="Collection.html#optional-restrictions">optional</a>) 903 * @since 1.8 904 */ 905 default V computeIfPresent(K key, 906 BiFunction<? super K, ? super V, ? extends V> remappingFunction) { 907 V oldValue; 908 while ((oldValue = get(key)) != null) { 909 V newValue = remappingFunction.apply(key, oldValue); 910 if (newValue != null) { 911 if (replace(key, oldValue, newValue)) 912 return newValue; 913 } else if (remove(key, oldValue)) 914 return null; 915 } 916 return oldValue; 917 } 918 919 /** 920 * Attempts to compute a mapping for the specified key and its 921 * current mapped value (or {@code null} if there is no current 922 * mapping). For example, to either create or append a {@code 923 * String msg} to a value mapping: 924 * 925 * <pre> {@code 926 * map.compute(key, (k, v) -> (v == null) ? msg : v.concat(msg))}</pre> 927 * (Method {@link #merge merge()} is often simpler to use for such purposes.) 928 * 929 * <p>If the function returns {@code null}, the mapping is removed (or 930 * remains absent if initially absent). If the function itself throws an 931 * (unchecked) exception, the exception is rethrown, and the current mapping 932 * is left unchanged. 933 * 934 * <p>The default implementation makes no guarantees about synchronization 935 * or atomicity properties of this method. Any implementation providing 936 * atomicity guarantees must override this method and document its 937 * concurrency properties. In particular, all implementations of 938 * subinterface {@link java.util.concurrent.ConcurrentMap} must document 939 * whether the function is applied once atomically only if the value is not 940 * present. Any class that permits null values must document 941 * whether and how this method distinguishes absence from null mappings. 942 * 943 * @implSpec 944 * The default implementation is equivalent to performing the following 945 * steps for this {@code map}, then returning the current value or 946 * {@code null} if absent: 947 * 948 * <pre> {@code 949 * V oldValue = map.get(key); 950 * V newValue = remappingFunction.apply(key, oldValue); 951 * if (oldValue != null ) { 952 * if (newValue != null) 953 * map.replace(key, oldValue, newValue); 954 * else 955 * map.remove(key, oldValue); 956 * } else { 957 * if (newValue != null) 958 * map.putIfAbsent(key, newValue); 959 * else 960 * return null; 961 * } 962 * }</pre> 963 * 964 * In concurrent contexts, the default implementation may retry 965 * these steps when multiple threads attempt updates. 966 * 967 * @param key key with which the specified value is to be associated 968 * @param remappingFunction the function to compute a value 969 * @return the new value associated with the specified key, or null if none 970 * @throws NullPointerException if the specified key is null and 971 * this map does not support null keys, or the 972 * remappingFunction is null 973 * @throws UnsupportedOperationException if the {@code put} operation 974 * is not supported by this map 975 * (<a href="Collection.html#optional-restrictions">optional</a>) 976 * @throws ClassCastException if the class of the specified key or value 977 * prevents it from being stored in this map 978 * (<a href="Collection.html#optional-restrictions">optional</a>) 979 * @since 1.8 980 */ 981 default V compute(K key, 982 BiFunction<? super K, ? super V, ? extends V> remappingFunction) { 983 V oldValue = get(key); 984 for (;;) { 985 V newValue = remappingFunction.apply(key, oldValue); 986 if (oldValue != null) { 987 if (newValue != null) { 988 if (replace(key, oldValue, newValue)) 989 return newValue; 990 } else if (remove(key, oldValue)) { 991 return null; 992 } 993 oldValue = get(key); 994 } else { 995 if (newValue != null) { 996 if ((oldValue = putIfAbsent(key, newValue)) == null) 997 return newValue; 998 } else { 999 return null; 1000 } 1001 } 1002 } 1003 } 1004 1005 /** 1006 * If the specified key is not already associated with a value or is 1007 * associated with null, associates it with the given value. 1008 * Otherwise, replaces the value with the results of the given 1009 * remapping function, or removes if the result is {@code null}. This 1010 * method may be of use when combining multiple mapped values for a key. 1011 * For example, to either create or append a {@code String msg} to a 1012 * value mapping: 1013 * 1014 * <pre> {@code 1015 * map.merge(key, msg, String::concat) 1016 * }</pre> 1017 * 1018 * <p>If the function returns {@code null}, the mapping is removed (or 1019 * remains absent if initially absent). If the function itself throws an 1020 * (unchecked) exception, the exception is rethrown, and the current mapping 1021 * is left unchanged. 1022 * 1023 * <p>The default implementation makes no guarantees about synchronization 1024 * or atomicity properties of this method. Any implementation providing 1025 * atomicity guarantees must override this method and document its 1026 * concurrency properties. In particular, all implementations of 1027 * subinterface {@link java.util.concurrent.ConcurrentMap} must document 1028 * whether the function is applied once atomically only if the value is not 1029 * present. Any class that permits null values must document 1030 * whether and how this method distinguishes absence from null mappings. 1031 * 1032 * @implSpec 1033 * The default implementation is equivalent to performing the 1034 * following steps for this {@code map}, then returning the 1035 * current value or {@code null} if absent: 1036 * 1037 * <pre> {@code 1038 * V oldValue = map.get(key); 1039 * V newValue = (oldValue == null) ? value : 1040 * remappingFunction.apply(oldValue, value); 1041 * if (newValue == null) 1042 * map.remove(key, oldValue); 1043 * else if (oldValue == null) 1044 * map.putIfAbsent(key, newValue); 1045 * else 1046 * map.replace(key, oldValue, newValue); 1047 * }</pre> 1048 * 1049 * In concurrent contexts, the default implementation may retry 1050 * these steps when multiple threads attempt updates. 1051 * 1052 * @param key key with which the specified value is to be associated 1053 * @param value the value to use if absent 1054 * @param remappingFunction the function to recompute a value if present 1055 * @return the new value associated with the specified key, or null if none 1056 * @throws UnsupportedOperationException if the {@code put} operation 1057 * is not supported by this map 1058 * (<a href="Collection.html#optional-restrictions">optional</a>) 1059 * @throws ClassCastException if the class of the specified key or value 1060 * prevents it from being stored in this map 1061 * (<a href="Collection.html#optional-restrictions">optional</a>) 1062 * @throws NullPointerException if the specified key is null and 1063 * this map does not support null keys, or the 1064 * remappingFunction is null 1065 * @since 1.8 1066 */ 1067 default V merge(K key, V value, 1068 BiFunction<? super V, ? super V, ? extends V> remappingFunction) { 1069 V oldValue = get(key); 1070 for (;;) { 1071 if (oldValue != null) { 1072 V newValue = remappingFunction.apply(oldValue, value); 1073 if (newValue != null) { 1074 if (replace(key, oldValue, newValue)) 1075 return newValue; 1076 } else if (remove(key, oldValue)) { 1077 return null; 1078 } 1079 oldValue = get(key); 1080 } else { 1081 if (value == null) { 1082 return null; 1083 } 1084 1085 if ((oldValue = putIfAbsent(key, value)) == null) { 1086 return value; 1087 } 1088 } 1089 } 1090 } 1091 }