Merge branch 'master' into BAEL-20573

This commit is contained in:
Krzysztof Woyke 2020-01-03 07:57:17 +01:00
commit 471915fb3c
3 changed files with 41 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);
}

View File

@ -3,6 +3,10 @@ package com.baeldung.autowire.sample;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
/**
* This class presents a field, a constructor, and a setter injection type.
* Usually, we'd stick with a single approach for a given property. This is just an educational code.
*/
@Component
public class FooService {
@ -10,6 +14,16 @@ public class FooService {
@FormatterType("Foo")
private Formatter formatter;
@Autowired
public FooService(@FormatterType("Foo") Formatter formatter) {
this.formatter = formatter;
}
@Autowired
public void setFormatter(@FormatterType("Foo") Formatter formatter) {
this.formatter = formatter;
}
public String doStuff() {
return formatter.format();
}