# 如何計算Arraylist中的重複元素

## 2.使用`Map.put()`循環

• 如果`resultMap`包含元素，我們將計數器增加1
• 否則，我們在HashMap上`put`一個新的Map條目`(element, 1)`
``````public <T> Map<T, Long> countByClassicalLoop(List<T> inputList) {

Map<T, Long> resultMap = new HashMap<>();

for (T element : inputList) {

if (resultMap.containsKey(element)) {

resultMap.put(element, resultMap.get(element) + 1L);

} else {

resultMap.put(element, 1L);

}

}

return resultMap;

}``````

``````public <T> Map<T, Long> countByForEachLoopWithGetOrDefault(List<T> inputList) {

Map<T, Long> resultMap = new HashMap<>();

inputList.forEach(e -> resultMap.put(e, resultMap.getOrDefault(e, 0L) + 1L));

return resultMap;

}``````

``````private List<String> INPUT_LIST = Lists.list(

"expect1",

"expect2", "expect2",

"expect3", "expect3", "expect3",

"expect4", "expect4", "expect4", "expect4");
``````

``````private void verifyResult(Map<String, Long> resultMap) {

assertThat(resultMap)

.isNotEmpty().hasSize(4)

.containsExactly(

entry("expect1", 1L),

entry("expect2", 2L),

entry("expect3", 3L),

entry("expect4", 4L));

}
``````

## 3.使用`Map.compute()`循環

``````public <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;

}``````

## 4.使用`Map.merge()`循環

``````public <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;

}``````

## 5.流API `Collectors.toMap()`

`toMap()`收集器可幫助我們將輸入列表轉換為`Map`

``````public <T> Map<T, Long> countByStreamToMap(List<T> inputList) {

return inputList.stream().collect(Collectors.toMap(Function.identity(), v -> 1L, Long::sum));

}``````

`toMap()`是一個方便的收集器，可以幫助我們將流轉換為不同的`Map`實現。

## 6.流API `Collectors.groupingBy()`和`Collectors.counting()`

``````public <T> Map<T, Long> countByStreamGroupBy(List<T> inputList) {

return inputList.stream().collect(Collectors.groupingBy(k -> k, Collectors.counting()));

}``````

## 7.結論

0 條評論，你可以發表評論，我們會進行改進