BAEL-3608: Add Map.merge() usage example (#8455)

This commit is contained in:
kwoyke 2020-01-03 07:51:16 +01:00 committed by Grzegorz Piwowarek
parent 130ba52379
commit c4497b7d3b
2 changed files with 27 additions and 7 deletions

View File

@ -24,11 +24,21 @@ public class DuplicatesCounter {
return resultMap;
}
public static <T> Map<T, Long> countByClassicalLoopWithMapCompute(List<T> inputList) {
public static <T> Map<T, Long> countByForEachLoopWithGetOrDefault(List<T> inputList) {
Map<T, Long> resultMap = new HashMap<>();
for (T element : inputList) {
resultMap.compute(element, (k, v) -> v == null ? 1 : v + 1);
}
inputList.forEach(e -> resultMap.put(e, resultMap.getOrDefault(e, 0L) + 1L));
return resultMap;
}
public static <T> Map<T, Long> countByForEachLoopWithMapCompute(List<T> inputList) {
Map<T, Long> resultMap = new HashMap<>();
inputList.forEach(e -> resultMap.compute(e, (k, v) -> v == null ? 1L : v + 1L));
return resultMap;
}
public static <T> Map<T, Long> countByForEachLoopWithMapMerge(List<T> inputList) {
Map<T, Long> resultMap = new HashMap<>();
inputList.forEach(e -> resultMap.merge(e, 1L, Long::sum));
return resultMap;
}

View File

@ -11,7 +11,6 @@ import static org.assertj.core.data.MapEntry.entry;
class DuplicatesCounterUnitTest {
private static List<String> INPUT_LIST = Lists.list(
"expect1",
"expect2", "expect2",
@ -24,10 +23,21 @@ class DuplicatesCounterUnitTest {
verifyResult(result);
}
@Test
void givenInput_whenCountByForEachLoopWithGetOrDefault_thenGetResultMap() {
Map<String, Long> result = DuplicatesCounter.countByForEachLoopWithGetOrDefault(INPUT_LIST);
verifyResult(result);
}
@Test
void givenInput_whenCountByClassicalLoopWithMapCompute_thenGetResultMap() {
Map<String, Long> result = DuplicatesCounter.countByClassicalLoopWithMapCompute(INPUT_LIST);
void givenInput_whenCountByForEachLoopWithMapCompute_thenGetResultMap() {
Map<String, Long> result = DuplicatesCounter.countByForEachLoopWithMapCompute(INPUT_LIST);
verifyResult(result);
}
@Test
void givenInput_whenCountByForEachLoopWithMapMerge_thenGetResultMap() {
Map<String, Long> result = DuplicatesCounter.countByForEachLoopWithMapMerge(INPUT_LIST);
verifyResult(result);
}