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