File tree 3 files changed +35
-2
lines changed
src/test/java/api/java/util/map
3 files changed +35
-2
lines changed Original file line number Diff line number Diff line change 18
18
19
19
Rudy Vissers [ Belgium]
20
20
21
- 122 tests
21
+ 120 tests
22
22
-
23
23
mvn clean install on Java 8 -> OK
24
24
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 ;
2
2
3
3
import org .junit .Test ;
4
4
You can’t perform that action at this time.
0 commit comments