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 import java.io.Serializable; 32 33 /** 34 * An object that maps keys to values. A map cannot contain duplicate keys; 35 * each key can map to at most one value. 36 * 37 * <p>This interface takes the place of the {@code Dictionary} class, which 38 * was a totally abstract class rather than an interface. 39 * 40 * <p>The {@code Map} interface provides three <i>collection views</i>, which 41 * allow a map's contents to be viewed as a set of keys, collection of values, 42 * or set of key-value mappings. The <i>order</i> of a map is defined as 43 * the order in which the iterators on the map's collection views return their 44 * elements. Some map implementations, like the {@code TreeMap} class, make 45 * specific guarantees as to their order; others, like the {@code HashMap} 46 * class, do not. 47 * 48 * <p>Note: great care must be exercised if mutable objects are used as map 49 * keys. The behavior of a map is not specified if the value of an object is 50 * changed in a manner that affects {@code equals} comparisons while the 51 * object is a key in the map. A special case of this prohibition is that it 52 * is not permissible for a map to contain itself as a key. While it is 53 * permissible for a map to contain itself as a value, extreme caution is 54 * advised: the {@code equals} and {@code hashCode} methods are no longer 55 * well defined on such a map. 56 * 57 * <p>All general-purpose map implementation classes should provide two 58 * "standard" constructors: a void (no arguments) constructor which creates an 59 * empty map, and a constructor with a single argument of type {@code Map}, 60 * which creates a new map with the same key-value mappings as its argument. 61 * In effect, the latter constructor allows the user to copy any map, 62 * producing an equivalent map of the desired class. There is no way to 63 * enforce this recommendation (as interfaces cannot contain constructors) but 64 * all of the general-purpose map implementations in the JDK comply. 65 * 66 * <p>The "destructive" methods contained in this interface, that is, the 67 * methods that modify the map on which they operate, are specified to throw 68 * {@code UnsupportedOperationException} if this map does not support the 69 * operation. If this is the case, these methods may, but are not required 70 * to, throw an {@code UnsupportedOperationException} if the invocation would 71 * have no effect on the map. For example, invoking the {@link #putAll(Map)} 72 * method on an unmodifiable map may, but is not required to, throw the 73 * exception if the map whose mappings are to be "superimposed" is empty. 74 * 75 * <p>Some map implementations have restrictions on the keys and values they 76 * may contain. For example, some implementations prohibit null keys and 77 * values, and some have restrictions on the types of their keys. Attempting 78 * to insert an ineligible key or value throws an unchecked exception, 79 * typically {@code NullPointerException} or {@code ClassCastException}. 80 * Attempting to query the presence of an ineligible key or value may throw an 81 * exception, or it may simply return false; some implementations will exhibit 82 * the former behavior and some will exhibit the latter. More generally, 83 * attempting an operation on an ineligible key or value whose completion 84 * would not result in the insertion of an ineligible element into the map may 85 * throw an exception or it may succeed, at the option of the implementation. 86 * Such exceptions are marked as "optional" in the specification for this 87 * interface. 88 * 89 * <p>Many methods in Collections Framework interfaces are defined 90 * in terms of the {@link Object#equals(Object) equals} method. For 91 * example, the specification for the {@link #containsKey(Object) 92 * containsKey(Object key)} method says: "returns {@code true} if and 93 * only if this map contains a mapping for a key {@code k} such that 94 * {@code (key==null ? k==null : key.equals(k))}." This specification should 95 * <i>not</i> be construed to imply that invoking {@code Map.containsKey} 96 * with a non-null argument {@code key} will cause {@code key.equals(k)} to 97 * be invoked for any key {@code k}. Implementations are free to 98 * implement optimizations whereby the {@code equals} invocation is avoided, 99 * for example, by first comparing the hash codes of the two keys. (The 100 * {@link Object#hashCode()} specification guarantees that two objects with 101 * unequal hash codes cannot be equal.) More generally, implementations of 102 * the various Collections Framework interfaces are free to take advantage of 103 * the specified behavior of underlying {@link Object} methods wherever the 104 * implementor deems it appropriate. 105 * 106 * <p>Some map operations which perform recursive traversal of the map may fail 107 * with an exception for self-referential instances where the map directly or 108 * indirectly contains itself. This includes the {@code clone()}, 109 * {@code equals()}, {@code hashCode()} and {@code toString()} methods. 110 * Implementations may optionally handle the self-referential scenario, however 111 * most current implementations do not do so. 112 * 113 * <h2><a name="immutable">Immutable Map Static Factory Methods</a></h2> 114 * <p>The {@link Map#of() Map.of()} and 115 * {@link Map#ofEntries(Map.Entry...) Map.ofEntries()} 116 * static factory methods provide a convenient way to create immutable maps. 117 * The {@code Map} 118 * instances created by these methods have the following characteristics: 119 * 120 * <ul> 121 * <li>They cannot be modified. Attempts to modify them result in 122 * an {@code UnsupportedOperationException}. 123 * <li>They are truly immutable only if the contained keys and values are themselves 124 * immutable. If a key or value is mutated, the behavior of the map is unspecified. 125 * <li>They disallow null keys and values. Attempts to create them with 126 * null keys or values result in {@code NullPointerException}. 127 * <li>They are serializable if all keys and values are serializable. 128 * <li>They reject duplicate keys at creation time. Duplicate keys 129 * passed to a static factory method result in {@code IllegalArgumentException}. 130 * </ul> 131 * 132 * <p>This interface is a member of the 133 * <a href="{@docRoot}/../technotes/guides/collections/index.html"> 134 * Java Collections Framework</a>. 135 * 136 * @param <K> the type of keys maintained by this map 137 * @param <V> the type of mapped values 138 * 139 * @author Josh Bloch 140 * @see HashMap 141 * @see TreeMap 142 * @see Hashtable 143 * @see SortedMap 144 * @see Collection 145 * @see Set 146 * @since 1.2 147 */ 148 public interface Map<K,V> { 149 // Query Operations 150 151 /** 152 * Returns the number of key-value mappings in this map. If the 153 * map contains more than {@code Integer.MAX_VALUE} elements, returns 154 * {@code Integer.MAX_VALUE}. 155 * 156 * @return the number of key-value mappings in this map 157 */ 158 int size(); 159 160 /** 161 * Returns {@code true} if this map contains no key-value mappings. 162 * 163 * @return {@code true} if this map contains no key-value mappings 164 */ 165 boolean isEmpty(); 166 167 /** 168 * Returns {@code true} if this map contains a mapping for the specified 169 * key. More formally, returns {@code true} if and only if 170 * this map contains a mapping for a key {@code k} such that 171 * {@code Objects.equals(key, k)}. (There can be 172 * at most one such mapping.) 173 * 174 * @param key key whose presence in this map is to be tested 175 * @return {@code true} if this map contains a mapping for the specified 176 * key 177 * @throws ClassCastException if the key is of an inappropriate type for 178 * this map 179 * (<a href="{@docRoot}/java/util/Collection.html#optional-restrictions">optional</a>) 180 * @throws NullPointerException if the specified key is null and this map 181 * does not permit null keys 182 * (<a href="{@docRoot}/java/util/Collection.html#optional-restrictions">optional</a>) 183 */ 184 boolean containsKey(Object key); 185 186 /** 187 * Returns {@code true} if this map maps one or more keys to the 188 * specified value. More formally, returns {@code true} if and only if 189 * this map contains at least one mapping to a value {@code v} such that 190 * {@code Objects.equals(value, v)}. This operation 191 * will probably require time linear in the map size for most 192 * implementations of the {@code Map} interface. 193 * 194 * @param value value whose presence in this map is to be tested 195 * @return {@code true} if this map maps one or more keys to the 196 * specified value 197 * @throws ClassCastException if the value is of an inappropriate type for 198 * this map 199 * (<a href="{@docRoot}/java/util/Collection.html#optional-restrictions">optional</a>) 200 * @throws NullPointerException if the specified value is null and this 201 * map does not permit null values 202 * (<a href="{@docRoot}/java/util/Collection.html#optional-restrictions">optional</a>) 203 */ 204 boolean containsValue(Object value); 205 206 /** 207 * Returns the value to which the specified key is mapped, 208 * or {@code null} if this map contains no mapping for the key. 209 * 210 * <p>More formally, if this map contains a mapping from a key 211 * {@code k} to a value {@code v} such that 212 * {@code Objects.equals(key, k)}, 213 * then this method returns {@code v}; otherwise 214 * it returns {@code null}. (There can be at most one such mapping.) 215 * 216 * <p>If this map permits null values, then a return value of 217 * {@code null} does not <i>necessarily</i> indicate that the map 218 * contains no mapping for the key; it's also possible that the map 219 * explicitly maps the key to {@code null}. The {@link #containsKey 220 * containsKey} operation may be used to distinguish these two cases. 221 * 222 * @param key the key whose associated value is to be returned 223 * @return the value to which the specified key is mapped, or 224 * {@code null} if this map contains no mapping for the key 225 * @throws ClassCastException if the key is of an inappropriate type for 226 * this map 227 * (<a href="{@docRoot}/java/util/Collection.html#optional-restrictions">optional</a>) 228 * @throws NullPointerException if the specified key is null and this map 229 * does not permit null keys 230 * (<a href="{@docRoot}/java/util/Collection.html#optional-restrictions">optional</a>) 231 */ 232 V get(Object key); 233 234 // Modification Operations 235 236 /** 237 * Associates the specified value with the specified key in this map 238 * (optional operation). If the map previously contained a mapping for 239 * the key, the old value is replaced by the specified value. (A map 240 * {@code m} is said to contain a mapping for a key {@code k} if and only 241 * if {@link #containsKey(Object) m.containsKey(k)} would return 242 * {@code true}.) 243 * 244 * @param key key with which the specified value is to be associated 245 * @param value value to be associated with the specified key 246 * @return the previous value associated with {@code key}, or 247 * {@code null} if there was no mapping for {@code key}. 248 * (A {@code null} return can also indicate that the map 249 * previously associated {@code null} with {@code key}, 250 * if the implementation supports {@code null} values.) 251 * @throws UnsupportedOperationException if the {@code put} operation 252 * is not supported by this map 253 * @throws ClassCastException if the class of the specified key or value 254 * prevents it from being stored in this map 255 * @throws NullPointerException if the specified key or value is null 256 * and this map does not permit null keys or values 257 * @throws IllegalArgumentException if some property of the specified key 258 * or value prevents it from being stored in this map 259 */ 260 V put(K key, V value); 261 262 /** 263 * Removes the mapping for a key from this map if it is present 264 * (optional operation). More formally, if this map contains a mapping 265 * from key {@code k} to value {@code v} such that 266 * {@code Objects.equals(key, k)}, that mapping 267 * is removed. (The map can contain at most one such mapping.) 268 * 269 * <p>Returns the value to which this map previously associated the key, 270 * or {@code null} if the map contained no mapping for the key. 271 * 272 * <p>If this map permits null values, then a return value of 273 * {@code null} does not <i>necessarily</i> indicate that the map 274 * contained no mapping for the key; it's also possible that the map 275 * explicitly mapped the key to {@code null}. 276 * 277 * <p>The map will not contain a mapping for the specified key once the 278 * call returns. 279 * 280 * @param key key whose mapping is to be removed from the map 281 * @return the previous value associated with {@code key}, or 282 * {@code null} if there was no mapping for {@code key}. 283 * @throws UnsupportedOperationException if the {@code remove} operation 284 * is not supported by this map 285 * @throws ClassCastException if the key is of an inappropriate type for 286 * this map 287 * (<a href="{@docRoot}/java/util/Collection.html#optional-restrictions">optional</a>) 288 * @throws NullPointerException if the specified key is null and this 289 * map does not permit null keys 290 * (<a href="{@docRoot}/java/util/Collection.html#optional-restrictions">optional</a>) 291 */ 292 V remove(Object key); 293 294 295 // Bulk Operations 296 297 /** 298 * Copies all of the mappings from the specified map to this map 299 * (optional operation). The effect of this call is equivalent to that 300 * of calling {@link #put(Object,Object) put(k, v)} on this map once 301 * for each mapping from key {@code k} to value {@code v} in the 302 * specified map. The behavior of this operation is undefined if the 303 * specified map is modified while the operation is in progress. 304 * 305 * @param m mappings to be stored in this map 306 * @throws UnsupportedOperationException if the {@code putAll} operation 307 * is not supported by this map 308 * @throws ClassCastException if the class of a key or value in the 309 * specified map prevents it from being stored in this map 310 * @throws NullPointerException if the specified map is null, or if 311 * this map does not permit null keys or values, and the 312 * specified map contains null keys or values 313 * @throws IllegalArgumentException if some property of a key or value in 314 * the specified map prevents it from being stored in this map 315 */ 316 void putAll(Map<? extends K, ? extends V> m); 317 318 /** 319 * Removes all of the mappings from this map (optional operation). 320 * The map will be empty after this call returns. 321 * 322 * @throws UnsupportedOperationException if the {@code clear} operation 323 * is not supported by this map 324 */ 325 void clear(); 326 327 328 // Views 329 330 /** 331 * Returns a {@link Set} view of the keys contained in this map. 332 * The set is backed by the map, so changes to the map are 333 * reflected in the set, and vice-versa. If the map is modified 334 * while an iteration over the set is in progress (except through 335 * the iterator's own {@code remove} operation), the results of 336 * the iteration are undefined. The set supports element removal, 337 * which removes the corresponding mapping from the map, via the 338 * {@code Iterator.remove}, {@code Set.remove}, 339 * {@code removeAll}, {@code retainAll}, and {@code clear} 340 * operations. It does not support the {@code add} or {@code addAll} 341 * operations. 342 * 343 * @return a set view of the keys contained in this map 344 */ 345 Set<K> keySet(); 346 347 /** 348 * Returns a {@link Collection} view of the values contained in this map. 349 * The collection is backed by the map, so changes to the map are 350 * reflected in the collection, and vice-versa. If the map is 351 * modified while an iteration over the collection is in progress 352 * (except through the iterator's own {@code remove} operation), 353 * the results of the iteration are undefined. The collection 354 * supports element removal, which removes the corresponding 355 * mapping from the map, via the {@code Iterator.remove}, 356 * {@code Collection.remove}, {@code removeAll}, 357 * {@code retainAll} and {@code clear} operations. It does not 358 * support the {@code add} or {@code addAll} operations. 359 * 360 * @return a collection view of the values contained in this map 361 */ 362 Collection<V> values(); 363 364 /** 365 * Returns a {@link Set} view of the mappings contained in this map. 366 * The set is backed by the map, so changes to the map are 367 * reflected in the set, and vice-versa. If the map is modified 368 * while an iteration over the set is in progress (except through 369 * the iterator's own {@code remove} operation, or through the 370 * {@code setValue} operation on a map entry returned by the 371 * iterator) the results of the iteration are undefined. The set 372 * supports element removal, which removes the corresponding 373 * mapping from the map, via the {@code Iterator.remove}, 374 * {@code Set.remove}, {@code removeAll}, {@code retainAll} and 375 * {@code clear} operations. It does not support the 376 * {@code add} or {@code addAll} operations. 377 * 378 * @return a set view of the mappings contained in this map 379 */ 380 Set<Map.Entry<K, V>> entrySet(); 381 382 /** 383 * A map entry (key-value pair). The {@code Map.entrySet} method returns 384 * a collection-view of the map, whose elements are of this class. The 385 * <i>only</i> way to obtain a reference to a map entry is from the 386 * iterator of this collection-view. These {@code Map.Entry} objects are 387 * valid <i>only</i> for the duration of the iteration; more formally, 388 * the behavior of a map entry is undefined if the backing map has been 389 * modified after the entry was returned by the iterator, except through 390 * the {@code setValue} operation on the map entry. 391 * 392 * @see Map#entrySet() 393 * @since 1.2 394 */ 395 interface Entry<K,V> { 396 /** 397 * Returns the key corresponding to this entry. 398 * 399 * @return the key corresponding to this entry 400 * @throws IllegalStateException implementations may, but are not 401 * required to, throw this exception if the entry has been 402 * removed from the backing map. 403 */ 404 K getKey(); 405 406 /** 407 * Returns the value corresponding to this entry. If the mapping 408 * has been removed from the backing map (by the iterator's 409 * {@code remove} operation), the results of this call are undefined. 410 * 411 * @return the value corresponding to this entry 412 * @throws IllegalStateException implementations may, but are not 413 * required to, throw this exception if the entry has been 414 * removed from the backing map. 415 */ 416 V getValue(); 417 418 /** 419 * Replaces the value corresponding to this entry with the specified 420 * value (optional operation). (Writes through to the map.) The 421 * behavior of this call is undefined if the mapping has already been 422 * removed from the map (by the iterator's {@code remove} operation). 423 * 424 * @param value new value to be stored in this entry 425 * @return old value corresponding to the entry 426 * @throws UnsupportedOperationException if the {@code put} operation 427 * is not supported by the backing map 428 * @throws ClassCastException if the class of the specified value 429 * prevents it from being stored in the backing map 430 * @throws NullPointerException if the backing map does not permit 431 * null values, and the specified value is null 432 * @throws IllegalArgumentException if some property of this value 433 * prevents it from being stored in the backing map 434 * @throws IllegalStateException implementations may, but are not 435 * required to, throw this exception if the entry has been 436 * removed from the backing map. 437 */ 438 V setValue(V value); 439 440 /** 441 * Compares the specified object with this entry for equality. 442 * Returns {@code true} if the given object is also a map entry and 443 * the two entries represent the same mapping. More formally, two 444 * entries {@code e1} and {@code e2} represent the same mapping 445 * if<pre> 446 * (e1.getKey()==null ? 447 * e2.getKey()==null : e1.getKey().equals(e2.getKey())) && 448 * (e1.getValue()==null ? 449 * e2.getValue()==null : e1.getValue().equals(e2.getValue())) 450 * </pre> 451 * This ensures that the {@code equals} method works properly across 452 * different implementations of the {@code Map.Entry} interface. 453 * 454 * @param o object to be compared for equality with this map entry 455 * @return {@code true} if the specified object is equal to this map 456 * entry 457 */ 458 boolean equals(Object o); 459 460 /** 461 * Returns the hash code value for this map entry. The hash code 462 * of a map entry {@code e} is defined to be: <pre> 463 * (e.getKey()==null ? 0 : e.getKey().hashCode()) ^ 464 * (e.getValue()==null ? 0 : e.getValue().hashCode()) 465 * </pre> 466 * This ensures that {@code e1.equals(e2)} implies that 467 * {@code e1.hashCode()==e2.hashCode()} for any two Entries 468 * {@code e1} and {@code e2}, as required by the general 469 * contract of {@code Object.hashCode}. 470 * 471 * @return the hash code value for this map entry 472 * @see Object#hashCode() 473 * @see Object#equals(Object) 474 * @see #equals(Object) 475 */ 476 int hashCode(); 477 478 /** 479 * Returns a comparator that compares {@link Map.Entry} in natural order on key. 480 * 481 * <p>The returned comparator is serializable and throws {@link 482 * NullPointerException} when comparing an entry with a null key. 483 * 484 * @param <K> the {@link Comparable} type of then map keys 485 * @param <V> the type of the map values 486 * @return a comparator that compares {@link Map.Entry} in natural order on key. 487 * @see Comparable 488 * @since 1.8 489 */ 490 public static <K extends Comparable<? super K>, V> Comparator<Map.Entry<K,V>> comparingByKey() { 491 return (Comparator<Map.Entry<K, V>> & Serializable) 492 (c1, c2) -> c1.getKey().compareTo(c2.getKey()); 493 } 494 495 /** 496 * Returns a comparator that compares {@link Map.Entry} in natural order on value. 497 * 498 * <p>The returned comparator is serializable and throws {@link 499 * NullPointerException} when comparing an entry with null values. 500 * 501 * @param <K> the type of the map keys 502 * @param <V> the {@link Comparable} type of the map values 503 * @return a comparator that compares {@link Map.Entry} in natural order on value. 504 * @see Comparable 505 * @since 1.8 506 */ 507 public static <K, V extends Comparable<? super V>> Comparator<Map.Entry<K,V>> comparingByValue() { 508 return (Comparator<Map.Entry<K, V>> & Serializable) 509 (c1, c2) -> c1.getValue().compareTo(c2.getValue()); 510 } 511 512 /** 513 * Returns a comparator that compares {@link Map.Entry} by key using the given 514 * {@link Comparator}. 515 * 516 * <p>The returned comparator is serializable if the specified comparator 517 * is also serializable. 518 * 519 * @param <K> the type of the map keys 520 * @param <V> the type of the map values 521 * @param cmp the key {@link Comparator} 522 * @return a comparator that compares {@link Map.Entry} by the key. 523 * @since 1.8 524 */ 525 public static <K, V> Comparator<Map.Entry<K, V>> comparingByKey(Comparator<? super K> cmp) { 526 Objects.requireNonNull(cmp); 527 return (Comparator<Map.Entry<K, V>> & Serializable) 528 (c1, c2) -> cmp.compare(c1.getKey(), c2.getKey()); 529 } 530 531 /** 532 * Returns a comparator that compares {@link Map.Entry} by value using the given 533 * {@link Comparator}. 534 * 535 * <p>The returned comparator is serializable if the specified comparator 536 * is also serializable. 537 * 538 * @param <K> the type of the map keys 539 * @param <V> the type of the map values 540 * @param cmp the value {@link Comparator} 541 * @return a comparator that compares {@link Map.Entry} by the value. 542 * @since 1.8 543 */ 544 public static <K, V> Comparator<Map.Entry<K, V>> comparingByValue(Comparator<? super V> cmp) { 545 Objects.requireNonNull(cmp); 546 return (Comparator<Map.Entry<K, V>> & Serializable) 547 (c1, c2) -> cmp.compare(c1.getValue(), c2.getValue()); 548 } 549 } 550 551 // Comparison and hashing 552 553 /** 554 * Compares the specified object with this map for equality. Returns 555 * {@code true} if the given object is also a map and the two maps 556 * represent the same mappings. More formally, two maps {@code m1} and 557 * {@code m2} represent the same mappings if 558 * {@code m1.entrySet().equals(m2.entrySet())}. This ensures that the 559 * {@code equals} method works properly across different implementations 560 * of the {@code Map} interface. 561 * 562 * @param o object to be compared for equality with this map 563 * @return {@code true} if the specified object is equal to this map 564 */ 565 boolean equals(Object o); 566 567 /** 568 * Returns the hash code value for this map. The hash code of a map is 569 * defined to be the sum of the hash codes of each entry in the map's 570 * {@code entrySet()} view. This ensures that {@code m1.equals(m2)} 571 * implies that {@code m1.hashCode()==m2.hashCode()} for any two maps 572 * {@code m1} and {@code m2}, as required by the general contract of 573 * {@link Object#hashCode}. 574 * 575 * @return the hash code value for this map 576 * @see Map.Entry#hashCode() 577 * @see Object#equals(Object) 578 * @see #equals(Object) 579 */ 580 int hashCode(); 581 582 // Defaultable methods 583 584 /** 585 * Returns the value to which the specified key is mapped, or 586 * {@code defaultValue} if this map contains no mapping for the key. 587 * 588 * @implSpec 589 * The default implementation makes no guarantees about synchronization 590 * or atomicity properties of this method. Any implementation providing 591 * atomicity guarantees must override this method and document its 592 * concurrency properties. 593 * 594 * @param key the key whose associated value is to be returned 595 * @param defaultValue the default mapping of the key 596 * @return the value to which the specified key is mapped, or 597 * {@code defaultValue} if this map contains no mapping for the key 598 * @throws ClassCastException if the key is of an inappropriate type for 599 * this map 600 * (<a href="{@docRoot}/java/util/Collection.html#optional-restrictions">optional</a>) 601 * @throws NullPointerException if the specified key is null and this map 602 * does not permit null keys 603 * (<a href="{@docRoot}/java/util/Collection.html#optional-restrictions">optional</a>) 604 * @since 1.8 605 */ 606 default V getOrDefault(Object key, V defaultValue) { 607 V v; 608 return (((v = get(key)) != null) || containsKey(key)) 609 ? v 610 : defaultValue; 611 } 612 613 /** 614 * Performs the given action for each entry in this map until all entries 615 * have been processed or the action throws an exception. Unless 616 * otherwise specified by the implementing class, actions are performed in 617 * the order of entry set iteration (if an iteration order is specified.) 618 * Exceptions thrown by the action are relayed to the caller. 619 * 620 * @implSpec 621 * The default implementation is equivalent to, for this {@code map}: 622 * <pre> {@code 623 * for (Map.Entry<K, V> entry : map.entrySet()) 624 * action.accept(entry.getKey(), entry.getValue()); 625 * }</pre> 626 * 627 * The default implementation makes no guarantees about synchronization 628 * or atomicity properties of this method. Any implementation providing 629 * atomicity guarantees must override this method and document its 630 * concurrency properties. 631 * 632 * @param action The action to be performed for each entry 633 * @throws NullPointerException if the specified action is null 634 * @throws ConcurrentModificationException if an entry is found to be 635 * removed during iteration 636 * @since 1.8 637 */ 638 default void forEach(BiConsumer<? super K, ? super V> action) { 639 Objects.requireNonNull(action); 640 for (Map.Entry<K, V> entry : entrySet()) { 641 K k; 642 V v; 643 try { 644 k = entry.getKey(); 645 v = entry.getValue(); 646 } catch(IllegalStateException ise) { 647 // this usually means the entry is no longer in the map. 648 throw new ConcurrentModificationException(ise); 649 } 650 action.accept(k, v); 651 } 652 } 653 654 /** 655 * Replaces each entry's value with the result of invoking the given 656 * function on that entry until all entries have been processed or the 657 * function throws an exception. Exceptions thrown by the function are 658 * relayed to the caller. 659 * 660 * @implSpec 661 * <p>The default implementation is equivalent to, for this {@code map}: 662 * <pre> {@code 663 * for (Map.Entry<K, V> entry : map.entrySet()) 664 * entry.setValue(function.apply(entry.getKey(), entry.getValue())); 665 * }</pre> 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 * @param function the function to apply to each entry 673 * @throws UnsupportedOperationException if the {@code set} operation 674 * is not supported by this map's entry set iterator. 675 * @throws ClassCastException if the class of a replacement value 676 * prevents it from being stored in this map 677 * @throws NullPointerException if the specified function is null, or the 678 * specified replacement value is null, and this map does not permit null 679 * values 680 * @throws ClassCastException if a replacement value is of an inappropriate 681 * type for this map 682 * (<a href="{@docRoot}/java/util/Collection.html#optional-restrictions">optional</a>) 683 * @throws NullPointerException if function or a replacement value is null, 684 * and this map does not permit null keys or values 685 * (<a href="{@docRoot}/java/util/Collection.html#optional-restrictions">optional</a>) 686 * @throws IllegalArgumentException if some property of a replacement value 687 * prevents it from being stored in this map 688 * (<a href="{@docRoot}/java/util/Collection.html#optional-restrictions">optional</a>) 689 * @throws ConcurrentModificationException if an entry is found to be 690 * removed during iteration 691 * @since 1.8 692 */ 693 default void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) { 694 Objects.requireNonNull(function); 695 for (Map.Entry<K, V> entry : entrySet()) { 696 K k; 697 V v; 698 try { 699 k = entry.getKey(); 700 v = entry.getValue(); 701 } catch(IllegalStateException ise) { 702 // this usually means the entry is no longer in the map. 703 throw new ConcurrentModificationException(ise); 704 } 705 706 // ise thrown from function is not a cme. 707 v = function.apply(k, v); 708 709 try { 710 entry.setValue(v); 711 } catch(IllegalStateException ise) { 712 // this usually means the entry is no longer in the map. 713 throw new ConcurrentModificationException(ise); 714 } 715 } 716 } 717 718 /** 719 * If the specified key is not already associated with a value (or is mapped 720 * to {@code null}) associates it with the given value and returns 721 * {@code null}, else returns the current value. 722 * 723 * @implSpec 724 * The default implementation is equivalent to, for this {@code 725 * map}: 726 * 727 * <pre> {@code 728 * V v = map.get(key); 729 * if (v == null) 730 * v = map.put(key, value); 731 * 732 * return v; 733 * }</pre> 734 * 735 * <p>The default implementation makes no guarantees about synchronization 736 * or atomicity properties of this method. Any implementation providing 737 * atomicity guarantees must override this method and document its 738 * concurrency properties. 739 * 740 * @param key key with which the specified value is to be associated 741 * @param value value to be associated with the specified key 742 * @return the previous value associated with the specified key, or 743 * {@code null} if there was no mapping for the key. 744 * (A {@code null} return can also indicate that the map 745 * previously associated {@code null} with the key, 746 * if the implementation supports null values.) 747 * @throws UnsupportedOperationException if the {@code put} operation 748 * is not supported by this map 749 * (<a href="{@docRoot}/java/util/Collection.html#optional-restrictions">optional</a>) 750 * @throws ClassCastException if the key or value is of an inappropriate 751 * type for this map 752 * (<a href="{@docRoot}/java/util/Collection.html#optional-restrictions">optional</a>) 753 * @throws NullPointerException if the specified key or value is null, 754 * and this map does not permit null keys or values 755 * (<a href="{@docRoot}/java/util/Collection.html#optional-restrictions">optional</a>) 756 * @throws IllegalArgumentException if some property of the specified key 757 * or value prevents it from being stored in this map 758 * (<a href="{@docRoot}/java/util/Collection.html#optional-restrictions">optional</a>) 759 * @since 1.8 760 */ 761 default V putIfAbsent(K key, V value) { 762 V v = get(key); 763 if (v == null) { 764 v = put(key, value); 765 } 766 767 return v; 768 } 769 770 /** 771 * Removes the entry for the specified key only if it is currently 772 * mapped to the specified value. 773 * 774 * @implSpec 775 * The default implementation is equivalent to, for this {@code map}: 776 * 777 * <pre> {@code 778 * if (map.containsKey(key) && Objects.equals(map.get(key), value)) { 779 * map.remove(key); 780 * return true; 781 * } else 782 * return false; 783 * }</pre> 784 * 785 * <p>The default implementation makes no guarantees about synchronization 786 * or atomicity properties of this method. Any implementation providing 787 * atomicity guarantees must override this method and document its 788 * concurrency properties. 789 * 790 * @param key key with which the specified value is associated 791 * @param value value expected to be associated with the specified key 792 * @return {@code true} if the value was removed 793 * @throws UnsupportedOperationException if the {@code remove} operation 794 * is not supported by this map 795 * (<a href="{@docRoot}/java/util/Collection.html#optional-restrictions">optional</a>) 796 * @throws ClassCastException if the key or value is of an inappropriate 797 * type for this map 798 * (<a href="{@docRoot}/java/util/Collection.html#optional-restrictions">optional</a>) 799 * @throws NullPointerException if the specified key or value is null, 800 * and this map does not permit null keys or values 801 * (<a href="{@docRoot}/java/util/Collection.html#optional-restrictions">optional</a>) 802 * @since 1.8 803 */ 804 default boolean remove(Object key, Object value) { 805 Object curValue = get(key); 806 if (!Objects.equals(curValue, value) || 807 (curValue == null && !containsKey(key))) { 808 return false; 809 } 810 remove(key); 811 return true; 812 } 813 814 /** 815 * Replaces the entry for the specified key only if currently 816 * mapped to the specified value. 817 * 818 * @implSpec 819 * The default implementation is equivalent to, for this {@code map}: 820 * 821 * <pre> {@code 822 * if (map.containsKey(key) && Objects.equals(map.get(key), value)) { 823 * map.put(key, newValue); 824 * return true; 825 * } else 826 * return false; 827 * }</pre> 828 * 829 * The default implementation does not throw NullPointerException 830 * for maps that do not support null values if oldValue is null unless 831 * newValue is also null. 832 * 833 * <p>The default implementation makes no guarantees about synchronization 834 * or atomicity properties of this method. Any implementation providing 835 * atomicity guarantees must override this method and document its 836 * concurrency properties. 837 * 838 * @param key key with which the specified value is associated 839 * @param oldValue value expected to be associated with the specified key 840 * @param newValue value to be associated with the specified key 841 * @return {@code true} if the value was replaced 842 * @throws UnsupportedOperationException if the {@code put} operation 843 * is not supported by this map 844 * (<a href="{@docRoot}/java/util/Collection.html#optional-restrictions">optional</a>) 845 * @throws ClassCastException if the class of a specified key or value 846 * prevents it from being stored in this map 847 * @throws NullPointerException if a specified key or newValue is null, 848 * and this map does not permit null keys or values 849 * @throws NullPointerException if oldValue is null and this map does not 850 * permit null values 851 * (<a href="{@docRoot}/java/util/Collection.html#optional-restrictions">optional</a>) 852 * @throws IllegalArgumentException if some property of a specified key 853 * or value prevents it from being stored in this map 854 * @since 1.8 855 */ 856 default boolean replace(K key, V oldValue, V newValue) { 857 Object curValue = get(key); 858 if (!Objects.equals(curValue, oldValue) || 859 (curValue == null && !containsKey(key))) { 860 return false; 861 } 862 put(key, newValue); 863 return true; 864 } 865 866 /** 867 * Replaces the entry for the specified key only if it is 868 * currently mapped to some value. 869 * 870 * @implSpec 871 * The default implementation is equivalent to, for this {@code map}: 872 * 873 * <pre> {@code 874 * if (map.containsKey(key)) { 875 * return map.put(key, value); 876 * } else 877 * return null; 878 * }</pre> 879 * 880 * <p>The default implementation makes no guarantees about synchronization 881 * or atomicity properties of this method. Any implementation providing 882 * atomicity guarantees must override this method and document its 883 * concurrency properties. 884 * 885 * @param key key with which the specified value is associated 886 * @param value value to be associated with the specified key 887 * @return the previous value associated with the specified key, or 888 * {@code null} if there was no mapping for the key. 889 * (A {@code null} return can also indicate that the map 890 * previously associated {@code null} with the key, 891 * if the implementation supports null values.) 892 * @throws UnsupportedOperationException if the {@code put} operation 893 * is not supported by this map 894 * (<a href="{@docRoot}/java/util/Collection.html#optional-restrictions">optional</a>) 895 * @throws ClassCastException if the class of the specified key or value 896 * prevents it from being stored in this map 897 * (<a href="{@docRoot}/java/util/Collection.html#optional-restrictions">optional</a>) 898 * @throws NullPointerException if the specified key or value is null, 899 * and this map does not permit null keys or values 900 * @throws IllegalArgumentException if some property of the specified key 901 * or value prevents it from being stored in this map 902 * @since 1.8 903 */ 904 default V replace(K key, V value) { 905 V curValue; 906 if (((curValue = get(key)) != null) || containsKey(key)) { 907 curValue = put(key, value); 908 } 909 return curValue; 910 } 911 912 /** 913 * If the specified key is not already associated with a value (or is mapped 914 * to {@code null}), attempts to compute its value using the given mapping 915 * function and enters it into this map unless {@code null}. 916 * 917 * <p>If the mapping function returns {@code null}, no mapping is recorded. 918 * If the mapping function itself throws an (unchecked) exception, the 919 * exception is rethrown, and no mapping is recorded. The most 920 * common usage is to construct a new object serving as an initial 921 * mapped value or memoized result, as in: 922 * 923 * <pre> {@code 924 * map.computeIfAbsent(key, k -> new Value(f(k))); 925 * }</pre> 926 * 927 * <p>Or to implement a multi-value map, {@code Map<K,Collection<V>>}, 928 * supporting multiple values per key: 929 * 930 * <pre> {@code 931 * map.computeIfAbsent(key, k -> new HashSet<V>()).add(v); 932 * }</pre> 933 * 934 * <p>The mapping function should not modify this map during computation. 935 * 936 * @implSpec 937 * The default implementation is equivalent to the following steps for this 938 * {@code map}, then returning the current value or {@code null} if now 939 * absent: 940 * 941 * <pre> {@code 942 * if (map.get(key) == null) { 943 * V newValue = mappingFunction.apply(key); 944 * if (newValue != null) 945 * map.put(key, newValue); 946 * } 947 * }</pre> 948 * 949 * <p>The default implementation makes no guarantees about detecting if the 950 * mapping function modifies this map during computation and, if 951 * appropriate, reporting an error. Non-concurrent implementations should 952 * override this method and, on a best-effort basis, throw a 953 * {@code ConcurrentModificationException} if it is detected that the 954 * mapping function modifies this map during computation. Concurrent 955 * implementations should override this method and, on a best-effort basis, 956 * throw an {@code IllegalStateException} if it is detected that the 957 * mapping function modifies this map during computation and as a result 958 * computation would never complete. 959 * 960 * <p>The default implementation makes no guarantees about synchronization 961 * or atomicity properties of this method. Any implementation providing 962 * atomicity guarantees must override this method and document its 963 * concurrency properties. In particular, all implementations of 964 * subinterface {@link java.util.concurrent.ConcurrentMap} must document 965 * whether the mapping function is applied once atomically only if the value 966 * is not present. 967 * 968 * @param key key with which the specified value is to be associated 969 * @param mappingFunction the mapping function to compute a value 970 * @return the current (existing or computed) value associated with 971 * the specified key, or null if the computed value is null 972 * @throws NullPointerException if the specified key is null and 973 * this map does not support null keys, or the mappingFunction 974 * is null 975 * @throws UnsupportedOperationException if the {@code put} operation 976 * is not supported by this map 977 * (<a href="{@docRoot}/java/util/Collection.html#optional-restrictions">optional</a>) 978 * @throws ClassCastException if the class of the specified key or value 979 * prevents it from being stored in this map 980 * (<a href="{@docRoot}/java/util/Collection.html#optional-restrictions">optional</a>) 981 * @since 1.8 982 */ 983 default V computeIfAbsent(K key, 984 Function<? super K, ? extends V> mappingFunction) { 985 Objects.requireNonNull(mappingFunction); 986 V v; 987 if ((v = get(key)) == null) { 988 V newValue; 989 if ((newValue = mappingFunction.apply(key)) != null) { 990 put(key, newValue); 991 return newValue; 992 } 993 } 994 995 return v; 996 } 997 998 /** 999 * If the value for the specified key is present and non-null, attempts to 1000 * compute a new mapping given the key and its current mapped value. 1001 * 1002 * <p>If the remapping function returns {@code null}, the mapping is removed. 1003 * If the remapping function itself throws an (unchecked) exception, the 1004 * exception is rethrown, and the current mapping is left unchanged. 1005 * 1006 * <p>The remapping function should not modify this map during computation. 1007 * 1008 * @implSpec 1009 * The default implementation is equivalent to performing the following 1010 * steps for this {@code map}, then returning the current value or 1011 * {@code null} if now absent: 1012 * 1013 * <pre> {@code 1014 * if (map.get(key) != null) { 1015 * V oldValue = map.get(key); 1016 * V newValue = remappingFunction.apply(key, oldValue); 1017 * if (newValue != null) 1018 * map.put(key, newValue); 1019 * else 1020 * map.remove(key); 1021 * } 1022 * }</pre> 1023 * 1024 * <p>The default implementation makes no guarantees about detecting if the 1025 * remapping function modifies this map during computation and, if 1026 * appropriate, reporting an error. Non-concurrent implementations should 1027 * override this method and, on a best-effort basis, throw a 1028 * {@code ConcurrentModificationException} if it is detected that the 1029 * remapping function modifies this map during computation. Concurrent 1030 * implementations should override this method and, on a best-effort basis, 1031 * throw an {@code IllegalStateException} if it is detected that the 1032 * remapping function modifies this map during computation and as a result 1033 * computation would never complete. 1034 * 1035 * <p>The default implementation makes no guarantees about synchronization 1036 * or atomicity properties of this method. Any implementation providing 1037 * atomicity guarantees must override this method and document its 1038 * concurrency properties. In particular, all implementations of 1039 * subinterface {@link java.util.concurrent.ConcurrentMap} must document 1040 * whether the remapping function is applied once atomically only if the 1041 * value is not present. 1042 * 1043 * @param key key with which the specified value is to be associated 1044 * @param remappingFunction the remapping function to compute a value 1045 * @return the new value associated with the specified key, or null if none 1046 * @throws NullPointerException if the specified key is null and 1047 * this map does not support null keys, or the 1048 * remappingFunction is null 1049 * @throws UnsupportedOperationException if the {@code put} operation 1050 * is not supported by this map 1051 * (<a href="{@docRoot}/java/util/Collection.html#optional-restrictions">optional</a>) 1052 * @throws ClassCastException if the class of the specified key or value 1053 * prevents it from being stored in this map 1054 * (<a href="{@docRoot}/java/util/Collection.html#optional-restrictions">optional</a>) 1055 * @since 1.8 1056 */ 1057 default V computeIfPresent(K key, 1058 BiFunction<? super K, ? super V, ? extends V> remappingFunction) { 1059 Objects.requireNonNull(remappingFunction); 1060 V oldValue; 1061 if ((oldValue = get(key)) != null) { 1062 V newValue = remappingFunction.apply(key, oldValue); 1063 if (newValue != null) { 1064 put(key, newValue); 1065 return newValue; 1066 } else { 1067 remove(key); 1068 return null; 1069 } 1070 } else { 1071 return null; 1072 } 1073 } 1074 1075 /** 1076 * Attempts to compute a mapping for the specified key and its current 1077 * mapped value (or {@code null} if there is no current mapping). For 1078 * example, to either create or append a {@code String} msg to a value 1079 * mapping: 1080 * 1081 * <pre> {@code 1082 * map.compute(key, (k, v) -> (v == null) ? msg : v.concat(msg))}</pre> 1083 * (Method {@link #merge merge()} is often simpler to use for such purposes.) 1084 * 1085 * <p>If the remapping function returns {@code null}, the mapping is removed 1086 * (or remains absent if initially absent). If the remapping function 1087 * itself throws an (unchecked) exception, the exception is rethrown, and 1088 * the current mapping is left unchanged. 1089 * 1090 * <p>The remapping function should not modify this map during computation. 1091 * 1092 * @implSpec 1093 * The default implementation is equivalent to performing the following 1094 * steps for this {@code map}, then returning the current value or 1095 * {@code null} if absent: 1096 * 1097 * <pre> {@code 1098 * V oldValue = map.get(key); 1099 * V newValue = remappingFunction.apply(key, oldValue); 1100 * if (oldValue != null ) { 1101 * if (newValue != null) 1102 * map.put(key, newValue); 1103 * else 1104 * map.remove(key); 1105 * } else { 1106 * if (newValue != null) 1107 * map.put(key, newValue); 1108 * else 1109 * return null; 1110 * } 1111 * }</pre> 1112 * 1113 * <p>The default implementation makes no guarantees about detecting if the 1114 * remapping function modifies this map during computation and, if 1115 * appropriate, reporting an error. Non-concurrent implementations should 1116 * override this method and, on a best-effort basis, throw a 1117 * {@code ConcurrentModificationException} if it is detected that the 1118 * remapping function modifies this map during computation. Concurrent 1119 * implementations should override this method and, on a best-effort basis, 1120 * throw an {@code IllegalStateException} if it is detected that the 1121 * remapping function modifies this map during computation and as a result 1122 * computation would never complete. 1123 * 1124 * <p>The default implementation makes no guarantees about synchronization 1125 * or atomicity properties of this method. Any implementation providing 1126 * atomicity guarantees must override this method and document its 1127 * concurrency properties. In particular, all implementations of 1128 * subinterface {@link java.util.concurrent.ConcurrentMap} must document 1129 * whether the remapping function is applied once atomically only if the 1130 * value is not present. 1131 * 1132 * @param key key with which the specified value is to be associated 1133 * @param remappingFunction the remapping function to compute a value 1134 * @return the new value associated with the specified key, or null if none 1135 * @throws NullPointerException if the specified key is null and 1136 * this map does not support null keys, or the 1137 * remappingFunction is null 1138 * @throws UnsupportedOperationException if the {@code put} operation 1139 * is not supported by this map 1140 * (<a href="{@docRoot}/java/util/Collection.html#optional-restrictions">optional</a>) 1141 * @throws ClassCastException if the class of the specified key or value 1142 * prevents it from being stored in this map 1143 * (<a href="{@docRoot}/java/util/Collection.html#optional-restrictions">optional</a>) 1144 * @since 1.8 1145 */ 1146 default V compute(K key, 1147 BiFunction<? super K, ? super V, ? extends V> remappingFunction) { 1148 Objects.requireNonNull(remappingFunction); 1149 V oldValue = get(key); 1150 1151 V newValue = remappingFunction.apply(key, oldValue); 1152 if (newValue == null) { 1153 // delete mapping 1154 if (oldValue != null || containsKey(key)) { 1155 // something to remove 1156 remove(key); 1157 return null; 1158 } else { 1159 // nothing to do. Leave things as they were. 1160 return null; 1161 } 1162 } else { 1163 // add or replace old mapping 1164 put(key, newValue); 1165 return newValue; 1166 } 1167 } 1168 1169 /** 1170 * If the specified key is not already associated with a value or is 1171 * associated with null, associates it with the given non-null value. 1172 * Otherwise, replaces the associated value with the results of the given 1173 * remapping function, or removes if the result is {@code null}. This 1174 * method may be of use when combining multiple mapped values for a key. 1175 * For example, to either create or append a {@code String msg} to a 1176 * value mapping: 1177 * 1178 * <pre> {@code 1179 * map.merge(key, msg, String::concat) 1180 * }</pre> 1181 * 1182 * <p>If the remapping function returns {@code null}, the mapping is removed. 1183 * If the remapping function itself throws an (unchecked) exception, the 1184 * exception is rethrown, and the current mapping is left unchanged. 1185 * 1186 * <p>The remapping function should not modify this map during computation. 1187 * 1188 * @implSpec 1189 * The default implementation is equivalent to performing the following 1190 * steps for this {@code map}, then returning the current value or 1191 * {@code null} if absent: 1192 * 1193 * <pre> {@code 1194 * V oldValue = map.get(key); 1195 * V newValue = (oldValue == null) ? value : 1196 * remappingFunction.apply(oldValue, value); 1197 * if (newValue == null) 1198 * map.remove(key); 1199 * else 1200 * map.put(key, newValue); 1201 * }</pre> 1202 * 1203 * <p>The default implementation makes no guarantees about detecting if the 1204 * remapping function modifies this map during computation and, if 1205 * appropriate, reporting an error. Non-concurrent implementations should 1206 * override this method and, on a best-effort basis, throw a 1207 * {@code ConcurrentModificationException} if it is detected that the 1208 * remapping function modifies this map during computation. Concurrent 1209 * implementations should override this method and, on a best-effort basis, 1210 * throw an {@code IllegalStateException} if it is detected that the 1211 * remapping function modifies this map during computation and as a result 1212 * computation would never complete. 1213 * 1214 * <p>The default implementation makes no guarantees about synchronization 1215 * or atomicity properties of this method. Any implementation providing 1216 * atomicity guarantees must override this method and document its 1217 * concurrency properties. In particular, all implementations of 1218 * subinterface {@link java.util.concurrent.ConcurrentMap} must document 1219 * whether the remapping function is applied once atomically only if the 1220 * value is not present. 1221 * 1222 * @param key key with which the resulting value is to be associated 1223 * @param value the non-null value to be merged with the existing value 1224 * associated with the key or, if no existing value or a null value 1225 * is associated with the key, to be associated with the key 1226 * @param remappingFunction the remapping function to recompute a value if 1227 * present 1228 * @return the new value associated with the specified key, or null if no 1229 * value is associated with the key 1230 * @throws UnsupportedOperationException if the {@code put} operation 1231 * is not supported by this map 1232 * (<a href="{@docRoot}/java/util/Collection.html#optional-restrictions">optional</a>) 1233 * @throws ClassCastException if the class of the specified key or value 1234 * prevents it from being stored in this map 1235 * (<a href="{@docRoot}/java/util/Collection.html#optional-restrictions">optional</a>) 1236 * @throws NullPointerException if the specified key is null and this map 1237 * does not support null keys or the value or remappingFunction is 1238 * null 1239 * @since 1.8 1240 */ 1241 default V merge(K key, V value, 1242 BiFunction<? super V, ? super V, ? extends V> remappingFunction) { 1243 Objects.requireNonNull(remappingFunction); 1244 Objects.requireNonNull(value); 1245 V oldValue = get(key); 1246 V newValue = (oldValue == null) ? value : 1247 remappingFunction.apply(oldValue, value); 1248 if(newValue == null) { 1249 remove(key); 1250 } else { 1251 put(key, newValue); 1252 } 1253 return newValue; 1254 } 1255 1256 /** 1257 * Creates an immutable map containing zero mappings. 1258 * See <a href="#immutable">Immutable Map Static Factory Methods</a> for details. 1259 * 1260 * @param <K> the map's key type 1261 * @param <V> the map's value type 1262 * @return the newly created map 1263 * 1264 * @since 9 1265 */ 1266 static <K,V> Map<K,V> of() { 1267 return Collections.emptyMap(); 1268 } 1269 1270 /** 1271 * Creates an immutable map containing a single mapping. 1272 * See <a href="#immutable">Immutable Map Static Factory Methods</a> for details. 1273 * 1274 * @param <K> the map's key type 1275 * @param <V> the map's value type 1276 * @param k1 the mapping's key 1277 * @param v1 the mapping's value 1278 * @return the newly created map 1279 * @throws NullPointerException if the key or the value is null 1280 * 1281 * @since 9 1282 */ 1283 static <K,V> Map<K,V> of(K k1, V v1) { 1284 return Collections.singletonMap(Objects.requireNonNull(k1), Objects.requireNonNull(v1)); 1285 } 1286 1287 /** 1288 * Creates an immutable map containing two mappings. 1289 * See <a href="#immutable">Immutable Map Static Factory Methods</a> for details. 1290 * 1291 * @param <K> the map's key type 1292 * @param <V> the map's value type 1293 * @param k1 the first mapping's key 1294 * @param v1 the first mapping's value 1295 * @param k2 the second mapping's key 1296 * @param v2 the second mapping's value 1297 * @return the newly created map 1298 * @throws IllegalArgumentException if the keys are duplicates 1299 * @throws NullPointerException if any key or value is null 1300 * 1301 * @since 9 1302 */ 1303 static <K,V> Map<K,V> of(K k1, V v1, K k2, V v2) { 1304 Map<K,V> map = new HashMap<>(3); 1305 map.put(Objects.requireNonNull(k1), Objects.requireNonNull(v1)); 1306 map.put(Objects.requireNonNull(k2), Objects.requireNonNull(v2)); 1307 if (map.size() != 2) { 1308 throw new IllegalArgumentException("duplicate keys"); 1309 } 1310 return Collections.unmodifiableMap(map); 1311 } 1312 1313 /** 1314 * Creates an immutable map containing three mappings. 1315 * See <a href="#immutable">Immutable Map Static Factory Methods</a> for details. 1316 * 1317 * @param <K> the map's key type 1318 * @param <V> the map's value type 1319 * @param k1 the first mapping's key 1320 * @param v1 the first mapping's value 1321 * @param k2 the second mapping's key 1322 * @param v2 the second mapping's value 1323 * @param k3 the third mapping's key 1324 * @param v3 the third mapping's value 1325 * @return the newly created map 1326 * @throws IllegalArgumentException if any keys are duplicates 1327 * @throws NullPointerException if any key or value is null 1328 * 1329 * @since 9 1330 */ 1331 static <K,V> Map<K,V> of(K k1, V v1, K k2, V v2, K k3, V v3) { 1332 Map<K,V> map = new HashMap<>(5); 1333 map.put(Objects.requireNonNull(k1), Objects.requireNonNull(v1)); 1334 map.put(Objects.requireNonNull(k2), Objects.requireNonNull(v2)); 1335 map.put(Objects.requireNonNull(k3), Objects.requireNonNull(v3)); 1336 if (map.size() != 3) { 1337 throw new IllegalArgumentException("duplicate keys"); 1338 } 1339 return Collections.unmodifiableMap(map); 1340 } 1341 1342 /** 1343 * Creates an immutable map containing four mappings. 1344 * See <a href="#immutable">Immutable Map Static Factory Methods</a> for details. 1345 * 1346 * @param <K> the map's key type 1347 * @param <V> the map's value type 1348 * @param k1 the first mapping's key 1349 * @param v1 the first mapping's value 1350 * @param k2 the second mapping's key 1351 * @param v2 the second mapping's value 1352 * @param k3 the third mapping's key 1353 * @param v3 the third mapping's value 1354 * @param k4 the fourth mapping's key 1355 * @param v4 the fourth mapping's value 1356 * @return the newly created map 1357 * @throws IllegalArgumentException if any keys are duplicates 1358 * @throws NullPointerException if any key or value is null 1359 * 1360 * @since 9 1361 */ 1362 static <K,V> Map<K,V> of(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4) { 1363 Map<K,V> map = new HashMap<>(6); 1364 map.put(Objects.requireNonNull(k1), Objects.requireNonNull(v1)); 1365 map.put(Objects.requireNonNull(k2), Objects.requireNonNull(v2)); 1366 map.put(Objects.requireNonNull(k3), Objects.requireNonNull(v3)); 1367 map.put(Objects.requireNonNull(k4), Objects.requireNonNull(v4)); 1368 if (map.size() != 4) { 1369 throw new IllegalArgumentException("duplicate keys"); 1370 } 1371 return Collections.unmodifiableMap(map); 1372 } 1373 1374 /** 1375 * Creates an immutable map containing five mappings. 1376 * See <a href="#immutable">Immutable Map Static Factory Methods</a> for details. 1377 * 1378 * @param <K> the map's key type 1379 * @param <V> the map's value type 1380 * @param k1 the first mapping's key 1381 * @param v1 the first mapping's value 1382 * @param k2 the second mapping's key 1383 * @param v2 the second mapping's value 1384 * @param k3 the third mapping's key 1385 * @param v3 the third mapping's value 1386 * @param k4 the fourth mapping's key 1387 * @param v4 the fourth mapping's value 1388 * @param k5 the fifth mapping's key 1389 * @param v5 the fifth mapping's value 1390 * @return the newly created map 1391 * @throws IllegalArgumentException if any keys are duplicates 1392 * @throws NullPointerException if any key or value is null 1393 * 1394 * @since 9 1395 */ 1396 static <K,V> Map<K,V> of(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5) { 1397 Map<K,V> map = new HashMap<>(7); 1398 map.put(Objects.requireNonNull(k1), Objects.requireNonNull(v1)); 1399 map.put(Objects.requireNonNull(k2), Objects.requireNonNull(v2)); 1400 map.put(Objects.requireNonNull(k3), Objects.requireNonNull(v3)); 1401 map.put(Objects.requireNonNull(k4), Objects.requireNonNull(v4)); 1402 map.put(Objects.requireNonNull(k5), Objects.requireNonNull(v5)); 1403 if (map.size() != 5) { 1404 throw new IllegalArgumentException("duplicate keys"); 1405 } 1406 return Collections.unmodifiableMap(map); 1407 } 1408 1409 /** 1410 * Creates an immutable map containing six mappings. 1411 * See <a href="#immutable">Immutable Map Static Factory Methods</a> for details. 1412 * 1413 * @param <K> the map's key type 1414 * @param <V> the map's value type 1415 * @param k1 the first mapping's key 1416 * @param v1 the first mapping's value 1417 * @param k2 the second mapping's key 1418 * @param v2 the second mapping's value 1419 * @param k3 the third mapping's key 1420 * @param v3 the third mapping's value 1421 * @param k4 the fourth mapping's key 1422 * @param v4 the fourth mapping's value 1423 * @param k5 the fifth mapping's key 1424 * @param v5 the fifth mapping's value 1425 * @param k6 the sixth mapping's key 1426 * @param v6 the sixth mapping's value 1427 * @return the newly created map 1428 * @throws IllegalArgumentException if any keys are duplicates 1429 * @throws NullPointerException if any key or value is null 1430 * 1431 * @since 9 1432 */ 1433 static <K,V> Map<K,V> of(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5, 1434 K k6, V v6) { 1435 Map<K,V> map = new HashMap<>(9); 1436 map.put(Objects.requireNonNull(k1), Objects.requireNonNull(v1)); 1437 map.put(Objects.requireNonNull(k2), Objects.requireNonNull(v2)); 1438 map.put(Objects.requireNonNull(k3), Objects.requireNonNull(v3)); 1439 map.put(Objects.requireNonNull(k4), Objects.requireNonNull(v4)); 1440 map.put(Objects.requireNonNull(k5), Objects.requireNonNull(v5)); 1441 map.put(Objects.requireNonNull(k6), Objects.requireNonNull(v6)); 1442 if (map.size() != 6) { 1443 throw new IllegalArgumentException("duplicate keys"); 1444 } 1445 return Collections.unmodifiableMap(map); 1446 } 1447 1448 /** 1449 * Creates an immutable map containing seven mappings. 1450 * See <a href="#immutable">Immutable Map Static Factory Methods</a> for details. 1451 * 1452 * @param <K> the map's key type 1453 * @param <V> the map's value type 1454 * @param k1 the first mapping's key 1455 * @param v1 the first mapping's value 1456 * @param k2 the second mapping's key 1457 * @param v2 the second mapping's value 1458 * @param k3 the third mapping's key 1459 * @param v3 the third mapping's value 1460 * @param k4 the fourth mapping's key 1461 * @param v4 the fourth mapping's value 1462 * @param k5 the fifth mapping's key 1463 * @param v5 the fifth mapping's value 1464 * @param k6 the sixth mapping's key 1465 * @param v6 the sixth mapping's value 1466 * @param k7 the seventh mapping's key 1467 * @param v7 the seventh mapping's value 1468 * @return the newly created map 1469 * @throws IllegalArgumentException if any keys are duplicates 1470 * @throws NullPointerException if any key or value is null 1471 * 1472 * @since 9 1473 */ 1474 static <K,V> Map<K,V> of(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5, 1475 K k6, V v6, K k7, V v7) { 1476 Map<K,V> map = new HashMap<>(10); 1477 map.put(Objects.requireNonNull(k1), Objects.requireNonNull(v1)); 1478 map.put(Objects.requireNonNull(k2), Objects.requireNonNull(v2)); 1479 map.put(Objects.requireNonNull(k3), Objects.requireNonNull(v3)); 1480 map.put(Objects.requireNonNull(k4), Objects.requireNonNull(v4)); 1481 map.put(Objects.requireNonNull(k5), Objects.requireNonNull(v5)); 1482 map.put(Objects.requireNonNull(k6), Objects.requireNonNull(v6)); 1483 map.put(Objects.requireNonNull(k7), Objects.requireNonNull(v7)); 1484 if (map.size() != 7) { 1485 throw new IllegalArgumentException("duplicate keys"); 1486 } 1487 return Collections.unmodifiableMap(map); 1488 } 1489 1490 /** 1491 * Creates an immutable map containing eight mappings. 1492 * See <a href="#immutable">Immutable Map Static Factory Methods</a> for details. 1493 * 1494 * @param <K> the map's key type 1495 * @param <V> the map's value type 1496 * @param k1 the first mapping's key 1497 * @param v1 the first mapping's value 1498 * @param k2 the second mapping's key 1499 * @param v2 the second mapping's value 1500 * @param k3 the third mapping's key 1501 * @param v3 the third mapping's value 1502 * @param k4 the fourth mapping's key 1503 * @param v4 the fourth mapping's value 1504 * @param k5 the fifth mapping's key 1505 * @param v5 the fifth mapping's value 1506 * @param k6 the sixth mapping's key 1507 * @param v6 the sixth mapping's value 1508 * @param k7 the seventh mapping's key 1509 * @param v7 the seventh mapping's value 1510 * @param k8 the eighth mapping's key 1511 * @param v8 the eighth mapping's value 1512 * @return the newly created map 1513 * @throws IllegalArgumentException if any keys are duplicates 1514 * @throws NullPointerException if any key or value is null 1515 * 1516 * @since 9 1517 */ 1518 static <K,V> Map<K,V> of(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5, 1519 K k6, V v6, K k7, V v7, K k8, V v8) { 1520 Map<K,V> map = new HashMap<>(11); 1521 map.put(Objects.requireNonNull(k1), Objects.requireNonNull(v1)); 1522 map.put(Objects.requireNonNull(k2), Objects.requireNonNull(v2)); 1523 map.put(Objects.requireNonNull(k3), Objects.requireNonNull(v3)); 1524 map.put(Objects.requireNonNull(k4), Objects.requireNonNull(v4)); 1525 map.put(Objects.requireNonNull(k5), Objects.requireNonNull(v5)); 1526 map.put(Objects.requireNonNull(k6), Objects.requireNonNull(v6)); 1527 map.put(Objects.requireNonNull(k7), Objects.requireNonNull(v7)); 1528 map.put(Objects.requireNonNull(k8), Objects.requireNonNull(v8)); 1529 if (map.size() != 8) { 1530 throw new IllegalArgumentException("duplicate keys"); 1531 } 1532 return Collections.unmodifiableMap(map); 1533 } 1534 1535 /** 1536 * Creates an immutable map containing nine mappings. 1537 * See <a href="#immutable">Immutable Map Static Factory Methods</a> for details. 1538 * 1539 * @param <K> the map's key type 1540 * @param <V> the map's value type 1541 * @param k1 the first mapping's key 1542 * @param v1 the first mapping's value 1543 * @param k2 the second mapping's key 1544 * @param v2 the second mapping's value 1545 * @param k3 the third mapping's key 1546 * @param v3 the third mapping's value 1547 * @param k4 the fourth mapping's key 1548 * @param v4 the fourth mapping's value 1549 * @param k5 the fifth mapping's key 1550 * @param v5 the fifth mapping's value 1551 * @param k6 the sixth mapping's key 1552 * @param v6 the sixth mapping's value 1553 * @param k7 the seventh mapping's key 1554 * @param v7 the seventh mapping's value 1555 * @param k8 the eighth mapping's key 1556 * @param v8 the eighth mapping's value 1557 * @param k9 the ninth mapping's key 1558 * @param v9 the ninth mapping's value 1559 * @return the newly created map 1560 * @throws IllegalArgumentException if any keys are duplicates 1561 * @throws NullPointerException if any key or value is null 1562 * 1563 * @since 9 1564 */ 1565 static <K,V> Map<K,V> of(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5, 1566 K k6, V v6, K k7, V v7, K k8, V v8, K k9, V v9) { 1567 Map<K,V> map = new HashMap<>(13); 1568 map.put(Objects.requireNonNull(k1), Objects.requireNonNull(v1)); 1569 map.put(Objects.requireNonNull(k2), Objects.requireNonNull(v2)); 1570 map.put(Objects.requireNonNull(k3), Objects.requireNonNull(v3)); 1571 map.put(Objects.requireNonNull(k4), Objects.requireNonNull(v4)); 1572 map.put(Objects.requireNonNull(k5), Objects.requireNonNull(v5)); 1573 map.put(Objects.requireNonNull(k6), Objects.requireNonNull(v6)); 1574 map.put(Objects.requireNonNull(k7), Objects.requireNonNull(v7)); 1575 map.put(Objects.requireNonNull(k8), Objects.requireNonNull(v8)); 1576 map.put(Objects.requireNonNull(k9), Objects.requireNonNull(v9)); 1577 if (map.size() != 9) { 1578 throw new IllegalArgumentException("duplicate keys"); 1579 } 1580 return Collections.unmodifiableMap(map); 1581 } 1582 1583 /** 1584 * Creates an immutable map containing ten mappings. 1585 * See <a href="#immutable">Immutable Map Static Factory Methods</a> for details. 1586 * 1587 * @param <K> the map's key type 1588 * @param <V> the map's value type 1589 * @param k1 the first mapping's key 1590 * @param v1 the first mapping's value 1591 * @param k2 the second mapping's key 1592 * @param v2 the second mapping's value 1593 * @param k3 the third mapping's key 1594 * @param v3 the third mapping's value 1595 * @param k4 the fourth mapping's key 1596 * @param v4 the fourth mapping's value 1597 * @param k5 the fifth mapping's key 1598 * @param v5 the fifth mapping's value 1599 * @param k6 the sixth mapping's key 1600 * @param v6 the sixth mapping's value 1601 * @param k7 the seventh mapping's key 1602 * @param v7 the seventh mapping's value 1603 * @param k8 the eighth mapping's key 1604 * @param v8 the eighth mapping's value 1605 * @param k9 the ninth mapping's key 1606 * @param v9 the ninth mapping's value 1607 * @param k10 the tenth mapping's key 1608 * @param v10 the tenth mapping's value 1609 * @return the newly created map 1610 * @throws IllegalArgumentException if any keys are duplicates 1611 * @throws NullPointerException if any key or value is null 1612 * 1613 * @since 9 1614 */ 1615 static <K,V> Map<K,V> of(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5, 1616 K k6, V v6, K k7, V v7, K k8, V v8, K k9, V v9, K k10, V v10) { 1617 Map<K,V> map = new HashMap<>(14); 1618 map.put(Objects.requireNonNull(k1), Objects.requireNonNull(v1)); 1619 map.put(Objects.requireNonNull(k2), Objects.requireNonNull(v2)); 1620 map.put(Objects.requireNonNull(k3), Objects.requireNonNull(v3)); 1621 map.put(Objects.requireNonNull(k4), Objects.requireNonNull(v4)); 1622 map.put(Objects.requireNonNull(k5), Objects.requireNonNull(v5)); 1623 map.put(Objects.requireNonNull(k6), Objects.requireNonNull(v6)); 1624 map.put(Objects.requireNonNull(k7), Objects.requireNonNull(v7)); 1625 map.put(Objects.requireNonNull(k8), Objects.requireNonNull(v8)); 1626 map.put(Objects.requireNonNull(k9), Objects.requireNonNull(v9)); 1627 map.put(Objects.requireNonNull(k10), Objects.requireNonNull(v10)); 1628 if (map.size() != 10) { 1629 throw new IllegalArgumentException("duplicate keys"); 1630 } 1631 return Collections.unmodifiableMap(map); 1632 } 1633 1634 /** 1635 * Creates an immutable map containing keys and values from the given entries. 1636 * See <a href="#immutable">Immutable Map Static Factory Methods</a> for details. 1637 * 1638 * @apiNote 1639 * It is convenient to create the map entries using the {@link Map#entry Map.entry()} method. 1640 * For example, 1641 * 1642 * <pre>{@code 1643 * import static java.util.Map.entry; 1644 * 1645 * Map<Integer,String> map = Map.ofEntries( 1646 * entry(1, "a"), 1647 * entry(2, "b"), 1648 * entry(3, "c"), 1649 * ... 1650 * entry(26, "z")); 1651 * }</pre> 1652 * 1653 * @param <K> the map's key type 1654 * @param <V> the map's value type 1655 * @param entries the keys and values with which the map is populated 1656 * @return the newly created {@code Map} 1657 * @throws IllegalArgumentException if any keys are duplicates 1658 * @throws NullPointerException if any entry, key, or value is null, or if 1659 * the {@code entries} array is null 1660 * 1661 * @see Map#entry Map.entry() 1662 * @since 9 1663 */ 1664 @SafeVarargs 1665 @SuppressWarnings("varargs") 1666 static <K,V> Map<K,V> ofEntries(Entry<K,V>... entries) { 1667 Map<K,V> map = new HashMap<>(entries.length * 4 / 3 + 1); // throws NPE if entries is null 1668 for (Entry<K,V> e : entries) { 1669 Objects.requireNonNull(e); 1670 map.put(Objects.requireNonNull(e.getKey()), Objects.requireNonNull(e.getValue())); 1671 } 1672 if (map.size() != entries.length) { 1673 throw new IllegalArgumentException("duplicate elements"); 1674 } 1675 return Collections.unmodifiableMap(map); 1676 } 1677 1678 /** 1679 * Creates an immutable {@link Entry} containing the given key and value. 1680 * These entries are suitable for populating {@code Map} instances using the 1681 * {@link Map#ofEntries Map.ofEntries()} method. 1682 * The key and the value must not be null. Calling {@link Entry#setValue Entry.setValue()} 1683 * on the returned {@code Entry} results in an {@code UnsupportedOperationException} 1684 * being thrown. The returned {@code Entry} is not guaranteed to be serializable. 1685 * 1686 * <p>The returned {@code Entry} is a <a href="../lang/doc-files/ValueBased.html">value-based</a> 1687 * class; use of identity-sensitive operations (including reference equality 1688 * ({@code ==}), identity hash code, or synchronization) on any returned values 1689 * may have unpredictable results and should be avoided. 1690 * 1691 * @param <K> the key's type 1692 * @param <V> the value's type 1693 * @param k the key 1694 * @param v the value 1695 * @return the new {@code Entry} 1696 * @throws NullPointerException if the key or value is null 1697 * 1698 * @see Map#ofEntries Map.ofEntries() 1699 * @since 9 1700 */ 1701 static <K,V> Entry<K,V> entry(K k, V v) { 1702 // KeyValueHolder checks for nulls 1703 return new KeyValueHolder<>(k, v); 1704 } 1705 }