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