Java HashMap计数:统计List集合中每个元素出现的次数
使用Java HashMap统计List元素出现次数
本文提供一个Java代码示例,演示如何使用HashMap统计List集合中每个元素出现的次数。
import java.util.*;
public class Main {
public static void main(String[] args) {
List<Integer> list = Arrays.asList(1, 2, 3, 2, 1, 3, 4, 5, 4, 6);
Map<Integer, Integer> map = new HashMap<>();
for (int num : list) {
if (map.containsKey(num)) {
map.put(num, map.get(num) + 1);
} else {
map.put(num, 1);
}
}
for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
System.out.println('Key: ' + entry.getKey() + ', Value: ' + entry.getValue());
}
}
}
代码解释:
-
创建数据结构:
List<Integer> list: 包含待统计元素的列表。Map<Integer, Integer> map: 用于存储元素和对应出现次数的HashMap,键为元素,值为出现次数。
-
遍历List:
- 使用增强for循环遍历
list中的每个元素num。
- 使用增强for循环遍历
-
统计出现次数:
map.containsKey(num): 检查map中是否已存在当前元素num作为键。- 若存在,则通过
map.get(num)获取当前元素的计数,将其加1后更新到map中。 - 若不存在,则将当前元素
num作为键,值为1(表示第一次出现)存入map。
- 若存在,则通过
-
输出结果:
- 使用
map.entrySet()遍历map中的所有键值对。 - 打印每个键值对,即元素和其对应的出现次数。
- 使用
运行结果:
Key: 1, Value: 2
Key: 2, Value: 2
Key: 3, Value: 2
Key: 4, Value: 2
Key: 5, Value: 1
Key: 6, Value: 1
该代码清晰地展示了如何利用HashMap高效地统计List集合中元素的出现频率。
原文地址: https://www.cveoy.top/t/topic/fK5T 著作权归作者所有。请勿转载和采集!