Skip to content

Commit 3622d94

Browse files
committed
Java HashMap
1 parent fe07ee1 commit 3622d94

1 file changed

Lines changed: 21 additions & 14 deletions

File tree

java-examples/java-core/src/test/java/com/hellokoding/java/collections/HashMapInitializeTest.java

Lines changed: 21 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,26 @@
77
import static org.assertj.core.api.Assertions.assertThat;
88

99
public class HashMapInitializeTest {
10+
@Test
11+
public void initInOneLineWithFactoryMethods() {
12+
// create and initialize a HashMap from Java 9+ Map.of
13+
Map<String, Integer> map1 = new HashMap<>((Map.of("k1", 1, "k3", 2, "k2", 3)));
14+
assertThat(map1).hasSize(3);
15+
16+
// create and initialize a HashMap from Java 9+ Map.ofEntries
17+
Map<String, Integer> map2 = new HashMap<>(Map.ofEntries(Map.entry("k4", 4), Map.entry("k5", 5)));
18+
assertThat(map2).hasSize(2);
19+
}
20+
21+
@Test
22+
public void initInOneLineFromAnExistingMap() {
23+
Map<String, Integer> map1 = new HashMap<>(Map.ofEntries(Map.entry("k4", 4), Map.entry("k5", 5)));
24+
25+
// create and initialize from an existing map
26+
Map<String, Integer> map2 = new HashMap<>(map1);
27+
assertThat(map2).hasSize(2);
28+
}
29+
1030
@Test
1131
public void initializeWithPut() {
1232
// Create a new HashMap
@@ -53,7 +73,7 @@ public void initializeWithPutIfAbsent() {
5373
}
5474

5575
@Test
56-
public void initializeWithPutInOneLine() {
76+
public void initializeWithDoubleBrace() {
5777
// Create a new HashMap
5878
Map<String, Integer> map = new HashMap<>(){{
5979
put("k1", 1);
@@ -86,18 +106,5 @@ public void initializeWithPutAll() {
86106
assertThat(map2).hasSize(5);
87107
}
88108

89-
@Test
90-
public void initializeFromAnotherMapWhenCreating() {
91-
// create and initialize a HashMap from Java 9+ Map.of
92-
Map<String, Integer> map1 = new HashMap<>((Map.of("k1", 1, "k3", 2, "k2", 3)));
93-
assertThat(map1).hasSize(3);
94109

95-
// create and initialize a HashMap from Java 9+ Map.ofEntries
96-
Map<String, Integer> map2 = new HashMap<>(Map.ofEntries(Map.entry("k4", 4), Map.entry("k5", 5)));
97-
assertThat(map2).hasSize(2);
98-
99-
// create and initialize from an existing map
100-
Map<String, Integer> map3 = new HashMap<>(map1);
101-
assertThat(map3).hasSize(3);
102-
}
103110
}

0 commit comments

Comments
 (0)