Skip to content

Commit 8c77986

Browse files
kwoykepivovarit
authored andcommitted
BAEL-3608: Add Map.merge() usage example (eugenp#8455)
1 parent 20bb9b6 commit 8c77986

2 files changed

Lines changed: 27 additions & 7 deletions

File tree

core-java-modules/core-java-collections-list-3/src/main/java/com/baeldung/list/duplicatescounter/DuplicatesCounter.java

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -24,11 +24,21 @@ public static <T> Map<T, Long> countByClassicalLoop(List<T> inputList) {
2424
return resultMap;
2525
}
2626

27-
public static <T> Map<T, Long> countByClassicalLoopWithMapCompute(List<T> inputList) {
27+
public static <T> Map<T, Long> countByForEachLoopWithGetOrDefault(List<T> inputList) {
2828
Map<T, Long> resultMap = new HashMap<>();
29-
for (T element : inputList) {
30-
resultMap.compute(element, (k, v) -> v == null ? 1 : v + 1);
31-
}
29+
inputList.forEach(e -> resultMap.put(e, resultMap.getOrDefault(e, 0L) + 1L));
30+
return resultMap;
31+
}
32+
33+
public static <T> Map<T, Long> countByForEachLoopWithMapCompute(List<T> inputList) {
34+
Map<T, Long> resultMap = new HashMap<>();
35+
inputList.forEach(e -> resultMap.compute(e, (k, v) -> v == null ? 1L : v + 1L));
36+
return resultMap;
37+
}
38+
39+
public static <T> Map<T, Long> countByForEachLoopWithMapMerge(List<T> inputList) {
40+
Map<T, Long> resultMap = new HashMap<>();
41+
inputList.forEach(e -> resultMap.merge(e, 1L, Long::sum));
3242
return resultMap;
3343
}
3444

core-java-modules/core-java-collections-list-3/src/test/java/com/baeldung/list/duplicatescounter/DuplicatesCounterUnitTest.java

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,6 @@
1111

1212
class DuplicatesCounterUnitTest {
1313

14-
1514
private static List<String> INPUT_LIST = Lists.list(
1615
"expect1",
1716
"expect2", "expect2",
@@ -24,10 +23,21 @@ void givenInput_whenCountByClassicalLoop_thenGetResultMap() {
2423
verifyResult(result);
2524
}
2625

26+
@Test
27+
void givenInput_whenCountByForEachLoopWithGetOrDefault_thenGetResultMap() {
28+
Map<String, Long> result = DuplicatesCounter.countByForEachLoopWithGetOrDefault(INPUT_LIST);
29+
verifyResult(result);
30+
}
31+
32+
@Test
33+
void givenInput_whenCountByForEachLoopWithMapCompute_thenGetResultMap() {
34+
Map<String, Long> result = DuplicatesCounter.countByForEachLoopWithMapCompute(INPUT_LIST);
35+
verifyResult(result);
36+
}
2737

2838
@Test
29-
void givenInput_whenCountByClassicalLoopWithMapCompute_thenGetResultMap() {
30-
Map<String, Long> result = DuplicatesCounter.countByClassicalLoopWithMapCompute(INPUT_LIST);
39+
void givenInput_whenCountByForEachLoopWithMapMerge_thenGetResultMap() {
40+
Map<String, Long> result = DuplicatesCounter.countByForEachLoopWithMapMerge(INPUT_LIST);
3141
verifyResult(result);
3242
}
3343

0 commit comments

Comments
 (0)