1 /*
2 * Copyright (c) 1997, 2011, 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 /**
29 * An object that maps keys to values. A map cannot contain duplicate keys;
30 * each key can map to at most one value.
31 *
32 * <p>This interface takes the place of the <tt>Dictionary</tt> class, which
33 * was a totally abstract class rather than an interface.
34 *
35 * <p>The <tt>Map</tt> interface provides three <i>collection views</i>, which
36 * allow a map's contents to be viewed as a set of keys, collection of values,
37 * or set of key-value mappings. The <i>order</i> of a map is defined as
38 * the order in which the iterators on the map's collection views return their
39 * elements. Some map implementations, like the <tt>TreeMap</tt> class, make
40 * specific guarantees as to their order; others, like the <tt>HashMap</tt>
41 * class, do not.
42 *
43 * <p>Note: great care must be exercised if mutable objects are used as map
44 * keys. The behavior of a map is not specified if the value of an object is
45 * changed in a manner that affects <tt>equals</tt> comparisons while the
46 * object is a key in the map. A special case of this prohibition is that it
47 * is not permissible for a map to contain itself as a key. While it is
458 * @param o object to be compared for equality with this map
459 * @return <tt>true</tt> if the specified object is equal to this map
460 */
461 boolean equals(Object o);
462
463 /**
464 * Returns the hash code value for this map. The hash code of a map is
465 * defined to be the sum of the hash codes of each entry in the map's
466 * <tt>entrySet()</tt> view. This ensures that <tt>m1.equals(m2)</tt>
467 * implies that <tt>m1.hashCode()==m2.hashCode()</tt> for any two maps
468 * <tt>m1</tt> and <tt>m2</tt>, as required by the general contract of
469 * {@link Object#hashCode}.
470 *
471 * @return the hash code value for this map
472 * @see Map.Entry#hashCode()
473 * @see Object#equals(Object)
474 * @see #equals(Object)
475 */
476 int hashCode();
477
478 }
|
1 /*
2 * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation. Oracle designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Oracle in the LICENSE file that accompanied this code.
10 *
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
16 *
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 *
21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 * or visit www.oracle.com if you need additional information or have any
23 * questions.
24 */
25
26 package java.util;
27
28 import java.util.function.BiConsumer;
29 import java.util.function.BiFunction;
30 import java.util.function.Function;
31
32 /**
33 * An object that maps keys to values. A map cannot contain duplicate keys;
34 * each key can map to at most one value.
35 *
36 * <p>This interface takes the place of the <tt>Dictionary</tt> class, which
37 * was a totally abstract class rather than an interface.
38 *
39 * <p>The <tt>Map</tt> interface provides three <i>collection views</i>, which
40 * allow a map's contents to be viewed as a set of keys, collection of values,
41 * or set of key-value mappings. The <i>order</i> of a map is defined as
42 * the order in which the iterators on the map's collection views return their
43 * elements. Some map implementations, like the <tt>TreeMap</tt> class, make
44 * specific guarantees as to their order; others, like the <tt>HashMap</tt>
45 * class, do not.
46 *
47 * <p>Note: great care must be exercised if mutable objects are used as map
48 * keys. The behavior of a map is not specified if the value of an object is
49 * changed in a manner that affects <tt>equals</tt> comparisons while the
50 * object is a key in the map. A special case of this prohibition is that it
51 * is not permissible for a map to contain itself as a key. While it is
462 * @param o object to be compared for equality with this map
463 * @return <tt>true</tt> if the specified object is equal to this map
464 */
465 boolean equals(Object o);
466
467 /**
468 * Returns the hash code value for this map. The hash code of a map is
469 * defined to be the sum of the hash codes of each entry in the map's
470 * <tt>entrySet()</tt> view. This ensures that <tt>m1.equals(m2)</tt>
471 * implies that <tt>m1.hashCode()==m2.hashCode()</tt> for any two maps
472 * <tt>m1</tt> and <tt>m2</tt>, as required by the general contract of
473 * {@link Object#hashCode}.
474 *
475 * @return the hash code value for this map
476 * @see Map.Entry#hashCode()
477 * @see Object#equals(Object)
478 * @see #equals(Object)
479 */
480 int hashCode();
481
482 // Defaultable methods
483
484 /**
485 * Returns the value to which the specified key is mapped,
486 * or {@code defaultValue} if this map contains no mapping
487 * for the key.
488 *
489 * <p>The default implementation makes no guarantees about synchronization
490 * or atomicity properties of this method. Any implementation providing
491 * atomicity guarantees must override this method and document its
492 * concurrency properties.
493 *
494 * @param key the key whose associated value is to be returned
495 * @return the value to which the specified key is mapped, or
496 * {@code defaultValue} if this map contains no mapping for the key
497 * @throws ClassCastException if the key is of an inappropriate type for
498 * this map
499 * (<a href="Collection.html#optional-restrictions">optional</a>)
500 * @throws NullPointerException if the specified key is null and this map
501 * does not permit null keys
502 * (<a href="Collection.html#optional-restrictions">optional</a>)
503 */
504 default V getOrDefault(Object key, V defaultValue) {
505 V v;
506 return (((v = get(key)) != null) || containsKey(key))
507 ? v
508 : defaultValue;
509 }
510
511 /**
512 * Performs the given action on each entry in this map, in the order entries
513 * are returned by an entry set iterator (which may be unspecified), until
514 * all entries have been processed or the action throws an {@code Exception}.
515 * Exceptions thrown by the action are relayed to the caller.
516 *
517 * <p>The default implementation should be overridden by implementations if
518 * they can provide a more performant implementation than an iterator-based
519 * one.
520 *
521 * <p>The default implementation makes no guarantees about synchronization
522 * or atomicity properties of this method. Any implementation providing
523 * atomicity guarantees must override this method and document its
524 * concurrency properties.
525 *
526 * @implSpec The default implementation is equivalent to, for this
527 * {@code map}:
528 * <pre> {@code
529 * for ((Map.Entry<K, V> entry : map.entrySet())
530 * action.accept(entry.getKey(), entry.getValue());
531 * }</pre>
532 *
533 * @param action The action to be performed for each entry
534 * @throws NullPointerException if the specified action is null
535 * @throws ConcurrentModificationException if an entry is found to be
536 * removed during iteration
537 * @since 1.8
538 */
539 default void forEach(BiConsumer<? super K, ? super V> action) {
540 Objects.requireNonNull(action);
541 for (Map.Entry<K, V> entry : entrySet()) {
542 K k;
543 V v;
544 try {
545 k = entry.getKey();
546 v = entry.getValue();
547 } catch(IllegalStateException ise) {
548 throw new ConcurrentModificationException(ise);
549 }
550 action.accept(k, v);
551 }
552 }
553
554 /**
555 * Replaces each entry's value with the result of invoking the given
556 * function on that entry, in the order entries are returned by an entry
557 * set iterator, until all entries have been processed or the function
558 * throws an exception.
559 *
560 * <p>The default implementation makes no guarantees about synchronization
561 * or atomicity properties of this method. Any implementation providing
562 * atomicity guarantees must override this method and document its
563 * concurrency properties.
564 *
565 * @implSpec
566 * <p>The default implementation is equivalent to, for this {@code map}:
567 * <pre> {@code
568 * for ((Map.Entry<K, V> entry : map.entrySet())
569 * entry.setValue(function.apply(entry.getKey(), entry.getValue()));
570 * }</pre>
571 *
572 * @param function the function to apply to each entry
573 * @throws UnsupportedOperationException if the {@code set} operation
574 * is not supported by this map's entry set iterator.
575 * @throws ClassCastException if the class of a replacement value
576 * prevents it from being stored in this map
577 * @throws NullPointerException if the specified function is null, or the
578 * specified replacement value is null, and this map does not permit null
579 * values
580 * @throws ClassCastException if a replacement value is of an inappropriate
581 * type for this map
582 * (<a href="Collection.html#optional-restrictions">optional</a>)
583 * @throws NullPointerException if function or a replacement value is null,
584 * and this map does not permit null keys or values
585 * (<a href="Collection.html#optional-restrictions">optional</a>)
586 * @throws IllegalArgumentException if some property of a replacement value
587 * prevents it from being stored in this map
588 * (<a href="Collection.html#optional-restrictions">optional</a>)
589 * @throws ConcurrentModificationException if an entry is found to be
590 * removed during iteration
591 * @since 1.8
592 */
593 default void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) {
594 Objects.requireNonNull(function);
595 for (Map.Entry<K, V> entry : entrySet()) {
596 K k;
597 V v;
598 try {
599 k = entry.getKey();
600 v = entry.getValue();
601 } catch(IllegalStateException ise) {
602 throw new ConcurrentModificationException(ise);
603 }
604 entry.setValue(function.apply(k, v));
605 }
606 }
607
608 /**
609 * If the specified key is not already associated with a value (or is mapped
610 * to {@code null}) associates it with the given value and returns
611 * {@code null}, else returns the current value.
612 *
613 * <p>The default implementation makes no guarantees about synchronization
614 * or atomicity properties of this method. Any implementation providing
615 * atomicity guarantees must override this method and document its
616 * concurrency properties.
617 *
618 * @implSpec
619 * The default implementation is equivalent to, for this {@code
620 * map}:
621 *
622 * <pre> {@code
623 * if (map.get(key) == null)
624 * return map.put(key, value);
625 * else
626 * return map.get(key);
627 * }</pre>
628 *
629 * @param key key with which the specified value is to be associated
630 * @param value value to be associated with the specified key
631 * @return the previous value associated with the specified key, or
632 * {@code 1} if there was no mapping for the key.
633 * (A {@code null} return can also indicate that the map
634 * previously associated {@code null} with the key,
635 * if the implementation supports null values.)
636 * @throws UnsupportedOperationException if the {@code put} operation
637 * is not supported by this map
638 * (<a href="Collection.html#optional-restrictions">optional</a>)
639 * @throws ClassCastException if the key or value is of an inappropriate
640 * type for this map
641 * (<a href="Collection.html#optional-restrictions">optional</a>)
642 * @throws NullPointerException if the specified key or value is null,
643 * and this map does not permit null keys or values
644 * (<a href="Collection.html#optional-restrictions">optional</a>)
645 * @throws IllegalArgumentException if some property of the specified key
646 * or value prevents it from being stored in this map
647 * (<a href="Collection.html#optional-restrictions">optional</a>)
648 * @throws ConcurrentModificationException if a modification of the map is
649 * detected during insertion of the value.
650 * @since 1.8
651 */
652 default V putIfAbsent(K key, V value) {
653 V v = get(key);
654 if (v == null) {
655 if (put(key, value) != null) {
656 throw new ConcurrentModificationException();
657 }
658 }
659
660 return v;
661 }
662
663 /**
664 * Removes the entry for the specified key only if it is currently
665 * mapped to the specified value.
666 *
667 * <p>The default implementation makes no guarantees about synchronization
668 * or atomicity properties of this method. Any implementation providing
669 * atomicity guarantees must override this method and document its
670 * concurrency properties.
671 *
672 * @implSpec
673 * The default implementation is equivalent to, for this {@code map}:
674 *
675 * <pre> {@code
676 * if (map.containsKey(key) && Objects.equals(map.get(key), value)) {
677 * map.remove(key);
678 * return true;
679 * } else
680 * return false;
681 * }</pre>
682 *
683 * @param key key with which the specified value is associated
684 * @param value value expected to be associated with the specified key
685 * @return {@code true} if the value was removed
686 * @throws UnsupportedOperationException if the {@code remove} operation
687 * is not supported by this map
688 * (<a href="Collection.html#optional-restrictions">optional</a>)
689 * @throws ClassCastException if the key or value is of an inappropriate
690 * type for this map
691 * (<a href="Collection.html#optional-restrictions">optional</a>)
692 * @throws NullPointerException if the specified key or value is null,
693 * and this map does not permit null keys or values
694 * (<a href="Collection.html#optional-restrictions">optional</a>)
695 * @since 1.8
696 */
697 default boolean remove(Object key, Object value) {
698 Object curValue = get(key);
699 if (!Objects.equals(curValue, value) ||
700 (curValue == null && !containsKey(key))) {
701 return false;
702 }
703 remove(key);
704 return true;
705 }
706
707 /**
708 * Replaces the entry for the specified key only if currently
709 * mapped to the specified value.
710 *
711 * <p>The default implementation makes no guarantees about synchronization
712 * or atomicity properties of this method. Any implementation providing
713 * atomicity guarantees must override this method and document its
714 * concurrency properties.
715 *
716 * @implSpec
717 * The default implementation is equivalent to, for this {@code map}:
718 *
719 * <pre> {@code
720 * if (map.containsKey(key) && Objects.equals(map.get(key), value)) {
721 * map.put(key, newValue);
722 * return true;
723 * } else
724 * return false;
725 * }</pre>
726 *
727 * @param key key with which the specified value is associated
728 * @param oldValue value expected to be associated with the specified key
729 * @param newValue value to be associated with the specified key
730 * @return {@code true} if the value was replaced
731 * @throws UnsupportedOperationException if the {@code put} operation
732 * is not supported by this map
733 * (<a href="Collection.html#optional-restrictions">optional</a>)
734 * @throws ClassCastException if the class of a specified key or value
735 * prevents it from being stored in this map
736 * @throws NullPointerException if a specified key or value is null,
737 * and this map does not permit null keys or values
738 * @throws IllegalArgumentException if some property of a specified key
739 * or value prevents it from being stored in this map
740 * @since 1.8
741 */
742 default boolean replace(K key, V oldValue, V newValue) {
743 Object curValue = get(key);
744 if (!Objects.equals(curValue, oldValue) ||
745 (curValue == null && !containsKey(key))) {
746 return false;
747 }
748 put(key, newValue);
749 return true;
750 }
751
752 /**
753 * Replaces the entry for the specified key only if it is
754 * currently mapped to some value.
755 *
756 * <p>The default implementation makes no guarantees about synchronization
757 * or atomicity properties of this method. Any implementation providing
758 * atomicity guarantees must override this method and document its
759 * concurrency properties.
760 *
761 * @implSpec
762 * The default implementation is equivalent to, for this {@code map}:
763 *
764 * <pre> {@code
765 * if (map.containsKey(key)) {
766 * return map.put(key, value);
767 * } else
768 * return null;
769 * }</pre>
770 *
771 * @param key key with which the specified value is associated
772 * @param value value to be associated with the specified key
773 * @return the previous value associated with the specified key, or
774 * {@code null} if there was no mapping for the key.
775 * (A {@code null} return can also indicate that the map
776 * previously associated {@code null} with the key,
777 * if the implementation supports null values.)
778 * @throws UnsupportedOperationException if the {@code put} operation
779 * is not supported by this map
780 * (<a href="Collection.html#optional-restrictions">optional</a>)
781 * @throws ClassCastException if the class of the specified key or value
782 * prevents it from being stored in this map
783 * (<a href="Collection.html#optional-restrictions">optional</a>)
784 * @throws NullPointerException if the specified key or value is null,
785 * and this map does not permit null keys or values
786 * @throws IllegalArgumentException if some property of the specified key
787 * or value prevents it from being stored in this map
788 * @since 1.8
789 */
790 default V replace(K key, V value) {
791 return containsKey(key) ? put(key, value) : null;
792 }
793
794 /**
795 * If the specified key is not already associated with a value (or
796 * is mapped to {@code null}), attempts to compute its value using
797 * the given mapping function and enters it into this map unless
798 * {@code null}.
799 *
800 * <p>If the function returns {@code null} no mapping is recorded. If
801 * the function itself throws an (unchecked) exception, the
802 * exception is rethrown, and no mapping is recorded. The most
803 * common usage is to construct a new object serving as an initial
804 * mapped value or memoized result, as in:
805 *
806 * <pre> {@code
807 * map.computeIfAbsent(key, k -> new Value(f(k)));
808 * }</pre>
809 *
810 * <p>The default implementation makes no guarantees about synchronization
811 * or atomicity properties of this method. Any implementation providing
812 * atomicity guarantees must override this method and document its
813 * concurrency properties. In particular, all implementations of
814 * subinterface {@link java.util.concurrent.ConcurrentMap} must document
815 * whether the function is applied once atomically only if the value is not
816 * present. Any class that permits null values must document
817 * whether and how this method distinguishes absence from null mappings.
818 *
819 * @implSpec
820 * The default implementation is equivalent to the following
821 * steps for this {@code map}, then returning the current value or
822 * {@code null} if now absent:
823 *
824 * <pre> {@code
825 * if (map.get(key) == null) {
826 * V newValue = mappingFunction.apply(key);
827 * if (newValue != null)
828 * map.putIfAbsent(key, newValue);
829 * }
830 * }</pre>
831 *
832 * @param key key with which the specified value is to be associated
833 * @param mappingFunction the function to compute a value
834 * @return the current (existing or computed) value associated with
835 * the specified key, or null if the computed value is null
836 * @throws NullPointerException if the specified key is null and
837 * this map does not support null keys, or the
838 * mappingFunction is null
839 * @throws UnsupportedOperationException if the {@code put} operation
840 * is not supported by this map
841 * (<a href="Collection.html#optional-restrictions">optional</a>)
842 * @throws ClassCastException if the class of the specified key or value
843 * prevents it from being stored in this map
844 * (<a href="Collection.html#optional-restrictions">optional</a>)
845 * @since 1.8
846 */
847 default V computeIfAbsent(K key,
848 Function<? super K, ? extends V> mappingFunction) {
849 V v, newValue;
850 return ((v = get(key)) == null &&
851 (newValue = mappingFunction.apply(key)) != null &&
852 (v = putIfAbsent(key, newValue)) == null) ? newValue : v;
853 }
854
855 /**
856 * If the value for the specified key is present and non-null, attempts to
857 * compute a new mapping given the key and its current mapped value.
858 *
859 * <p>If the function returns {@code null}, the mapping is removed. If the
860 * function itself throws an (unchecked) exception, the exception is
861 * rethrown, and the current mapping is left unchanged.
862 *
863 * <p>The default implementation makes no guarantees about synchronization
864 * or atomicity properties of this method. Any implementation providing
865 * atomicity guarantees must override this method and document its
866 * concurrency properties. In particular, all implementations of
867 * subinterface {@link java.util.concurrent.ConcurrentMap} must document
868 * whether the function is applied once atomically only if the value is not
869 * present. Any class that permits null values must document
870 * whether and how this method distinguishes absence from null mappings.
871 *
872 * @implSpec
873 * The default implementation is equivalent to performing the
874 * following steps for this {@code map}, then returning the
875 * current value or {@code null} if now absent:
876 *
877 * <pre> {@code
878 * if (map.get(key) != null) {
879 * V oldValue = map.get(key);
880 * V newValue = remappingFunction.apply(key, oldValue);
881 * if (newValue != null)
882 * map.replace(key, oldValue, newValue);
883 * else
884 * map.remove(key, oldValue);
885 * }
886 * }</pre>
887 *
888 * In concurrent contexts, the default implementation may retry
889 * these steps when multiple threads attempt updates.
890 *
891 * @param key key with which the specified value is to be associated
892 * @param remappingFunction the function to compute a value
893 * @return the new value associated with the specified key, or null if none
894 * @throws NullPointerException if the specified key is null and
895 * this map does not support null keys, or the
896 * remappingFunction is null
897 * @throws UnsupportedOperationException if the {@code put} operation
898 * is not supported by this map
899 * (<a href="Collection.html#optional-restrictions">optional</a>)
900 * @throws ClassCastException if the class of the specified key or value
901 * prevents it from being stored in this map
902 * (<a href="Collection.html#optional-restrictions">optional</a>)
903 * @since 1.8
904 */
905 default V computeIfPresent(K key,
906 BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
907 V oldValue;
908 while ((oldValue = get(key)) != null) {
909 V newValue = remappingFunction.apply(key, oldValue);
910 if (newValue != null) {
911 if (replace(key, oldValue, newValue))
912 return newValue;
913 } else if (remove(key, oldValue))
914 return null;
915 }
916 return oldValue;
917 }
918
919 /**
920 * Attempts to compute a mapping for the specified key and its
921 * current mapped value (or {@code null} if there is no current
922 * mapping). For example, to either create or append a {@code
923 * String msg} to a value mapping:
924 *
925 * <pre> {@code
926 * map.compute(key, (k, v) -> (v == null) ? msg : v.concat(msg))}</pre>
927 * (Method {@link #merge merge()} is often simpler to use for such purposes.)
928 *
929 * <p>If the function returns {@code null}, the mapping is removed (or
930 * remains absent if initially absent). If the function itself throws an
931 * (unchecked) exception, the exception is rethrown, and the current mapping
932 * is left unchanged.
933 *
934 * <p>The default implementation makes no guarantees about synchronization
935 * or atomicity properties of this method. Any implementation providing
936 * atomicity guarantees must override this method and document its
937 * concurrency properties. In particular, all implementations of
938 * subinterface {@link java.util.concurrent.ConcurrentMap} must document
939 * whether the function is applied once atomically only if the value is not
940 * present. Any class that permits null values must document
941 * whether and how this method distinguishes absence from null mappings.
942 *
943 * @implSpec
944 * The default implementation is equivalent to performing the following
945 * steps for this {@code map}, then returning the current value or
946 * {@code null} if absent:
947 *
948 * <pre> {@code
949 * V oldValue = map.get(key);
950 * V newValue = remappingFunction.apply(key, oldValue);
951 * if (oldValue != null ) {
952 * if (newValue != null)
953 * map.replace(key, oldValue, newValue);
954 * else
955 * map.remove(key, oldValue);
956 * } else {
957 * if (newValue != null)
958 * map.putIfAbsent(key, newValue);
959 * else
960 * return null;
961 * }
962 * }</pre>
963 *
964 * In concurrent contexts, the default implementation may retry
965 * these steps when multiple threads attempt updates.
966 *
967 * @param key key with which the specified value is to be associated
968 * @param remappingFunction the function to compute a value
969 * @return the new value associated with the specified key, or null if none
970 * @throws NullPointerException if the specified key is null and
971 * this map does not support null keys, or the
972 * remappingFunction is null
973 * @throws UnsupportedOperationException if the {@code put} operation
974 * is not supported by this map
975 * (<a href="Collection.html#optional-restrictions">optional</a>)
976 * @throws ClassCastException if the class of the specified key or value
977 * prevents it from being stored in this map
978 * (<a href="Collection.html#optional-restrictions">optional</a>)
979 * @since 1.8
980 */
981 default V compute(K key,
982 BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
983 V oldValue = get(key);
984 for (;;) {
985 V newValue = remappingFunction.apply(key, oldValue);
986 if (oldValue != null) {
987 if (newValue != null) {
988 if (replace(key, oldValue, newValue))
989 return newValue;
990 } else if (remove(key, oldValue)) {
991 return null;
992 }
993 oldValue = get(key);
994 } else {
995 if (newValue != null) {
996 if ((oldValue = putIfAbsent(key, newValue)) == null)
997 return newValue;
998 } else {
999 return null;
1000 }
1001 }
1002 }
1003 }
1004
1005 /**
1006 * If the specified key is not already associated with a value or is
1007 * associated with null, associates it with the given value.
1008 * Otherwise, replaces the value with the results of the given
1009 * remapping function, or removes if the result is {@code null}. This
1010 * method may be of use when combining multiple mapped values for a key.
1011 * For example, to either create or append a {@code String msg} to a
1012 * value mapping:
1013 *
1014 * <pre> {@code
1015 * map.merge(key, msg, String::concat)
1016 * }</pre>
1017 *
1018 * <p>If the function returns {@code null}, the mapping is removed (or
1019 * remains absent if initially absent). If the function itself throws an
1020 * (unchecked) exception, the exception is rethrown, and the current mapping
1021 * is left unchanged.
1022 *
1023 * <p>The default implementation makes no guarantees about synchronization
1024 * or atomicity properties of this method. Any implementation providing
1025 * atomicity guarantees must override this method and document its
1026 * concurrency properties. In particular, all implementations of
1027 * subinterface {@link java.util.concurrent.ConcurrentMap} must document
1028 * whether the function is applied once atomically only if the value is not
1029 * present. Any class that permits null values must document
1030 * whether and how this method distinguishes absence from null mappings.
1031 *
1032 * @implSpec
1033 * The default implementation is equivalent to performing the
1034 * following steps for this {@code map}, then returning the
1035 * current value or {@code null} if absent:
1036 *
1037 * <pre> {@code
1038 * V oldValue = map.get(key);
1039 * V newValue = (oldValue == null) ? value :
1040 * remappingFunction.apply(oldValue, value);
1041 * if (newValue == null)
1042 * map.remove(key, oldValue);
1043 * else if (oldValue == null)
1044 * map.putIfAbsent(key, newValue);
1045 * else
1046 * map.replace(key, oldValue, newValue);
1047 * }</pre>
1048 *
1049 * In concurrent contexts, the default implementation may retry
1050 * these steps when multiple threads attempt updates.
1051 *
1052 * @param key key with which the specified value is to be associated
1053 * @param value the value to use if absent
1054 * @param remappingFunction the function to recompute a value if present
1055 * @return the new value associated with the specified key, or null if none
1056 * @throws UnsupportedOperationException if the {@code put} operation
1057 * is not supported by this map
1058 * (<a href="Collection.html#optional-restrictions">optional</a>)
1059 * @throws ClassCastException if the class of the specified key or value
1060 * prevents it from being stored in this map
1061 * (<a href="Collection.html#optional-restrictions">optional</a>)
1062 * @throws NullPointerException if the specified key is null and
1063 * this map does not support null keys, or the
1064 * remappingFunction is null
1065 * @since 1.8
1066 */
1067 default V merge(K key, V value,
1068 BiFunction<? super V, ? super V, ? extends V> remappingFunction) {
1069 V oldValue = get(key);
1070 for (;;) {
1071 if (oldValue != null) {
1072 V newValue = remappingFunction.apply(oldValue, value);
1073 if (newValue != null) {
1074 if (replace(key, oldValue, newValue))
1075 return newValue;
1076 } else if (remove(key, oldValue)) {
1077 return null;
1078 }
1079 oldValue = get(key);
1080 } else {
1081 if (value == null) {
1082 return null;
1083 }
1084
1085 if ((oldValue = putIfAbsent(key, value)) == null) {
1086 return value;
1087 }
1088 }
1089 }
1090 }
1091 }
|