File tree Expand file tree Collapse file tree
src/test/java/api/java/util/map Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1818
1919Rudy Vissers [ Belgium]
2020
21- 122 tests
21+ 120 tests
2222-
2323mvn clean install on Java 8 -> OK
2424
Original file line number Diff line number Diff line change 1+ package api .java .util .map ;
2+
3+ import java .util .HashMap ;
4+ import java .util .Map ;
5+ public class MapComputeIfAbsentExample {
6+ public static void main (String [] args ) {
7+ // Create a map
8+ Map <String , Integer > scores = new HashMap <>();
9+
10+ // Retrieve the value for a key, or compute and store a new value if the key is absent
11+ int johnsScore = scores .computeIfAbsent ("John" , key -> computeScore (key ));
12+ System .out .println ("John's Score: " + johnsScore );
13+
14+ // Retrieve the existing value for a key
15+ int marysScore = scores .computeIfAbsent ("Mary" , key -> computeScore (key ));
16+ System .out .println ("Mary's Score: " + marysScore );
17+
18+ // Print the updated map
19+ System .out .println ("Updated Map: " + scores );
20+
21+ // Update the value of a non-absent key
22+ marysScore = scores .computeIfAbsent ("Mary" , key -> computeScore (key ) * 2 );
23+
24+ // Print the updated map
25+ System .out .println ("value of Map for Mary was not updated: " + scores );
26+ }
27+
28+ // A method to compute the score based on the key
29+ private static int computeScore (String key ) {
30+ System .out .println ("Computing score for: " + key );
31+ return key .length () * 10 ;
32+ }
33+ }
Original file line number Diff line number Diff line change 1- package api .java .util ;
1+ package api .java .util . map ;
22
33import org .junit .Test ;
44
You can’t perform that action at this time.
0 commit comments