Skip to content

Commit ebaf8ab

Browse files
author
m999rvi
committed
examples on Map
1 parent 66752af commit ebaf8ab

File tree

3 files changed

+35
-2
lines changed

3 files changed

+35
-2
lines changed

README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ Enjoy!
1818

1919
Rudy Vissers [Belgium]
2020

21-
122 tests
21+
120 tests
2222
-
2323
mvn clean install on Java 8 -> OK
2424

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
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+
}

src/test/java/api/java/util/MapTest.java renamed to src/test/java/api/java/util/map/MapTest.java

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
package api.java.util;
1+
package api.java.util.map;
22

33
import org.junit.Test;
44

0 commit comments

Comments
 (0)