可以通过Map统计List中重复元素的个数,方法一使用HashMap遍历List并累加计数,方法二利用Java 8 Stream API的groupingBy和counting更简洁实现,还可通过filter筛选出出现次数大于1的重复元素。

在Java中统计List中重复元素的个数,可以通过 Map 来记录每个元素出现的次数。常用的方式是使用 HashMap 遍历List并累加计数。
遍历List,将每个元素作为key,出现次数作为value存入Map。
import java.util.*;
public class CountDuplicates {
public static Map<String, Integer> countElements(List<String> list) {
Map<String, Integer> countMap = new HashMap<>();
for (String item : list) {
countMap.put(item, countMap.getOrDefault(item, 0) + 1);
}
return countMap;
}
public static void main(String[] args) {
List<String> items = Arrays.asList("apple", "banana", "apple", "orange", "banana", "apple");
Map<String, Integer> result = countElements(items);
System.out.println(result); // 输出: {orange=1, banana=2, apple=3}
}
}
利用 stream() 和 Collectors.groupingBy 可以更简洁地实现统计。
import java.util.*;
import java.util.stream.Collectors;
public class CountWithStream {
public static Map<String, Long> countElementsWithStream(List<String> list) {
return list.stream()
.collect(Collectors.groupingBy(e -> e, Collectors.counting()));
}
public static void main(String[] args) {
List<String> items = Arrays.asList("apple", "banana", "apple", "orange", "banana", "apple");
Map<String, Long> result = countElementsWithStream(items);
System.out.println(result); // 输出: {orange=1, banana=2, apple=3}
}
}
如果只想知道哪些元素是重复的,可以过滤出计数大于1的项。
立即学习“Java免费学习笔记(深入)”;
Map<String, Long> duplicates = list.stream()
.collect(Collectors.groupingBy(e -> e, Collectors.counting()))
.entrySet()
.stream()
.filter(entry -> entry.getValue() > 1)
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
以上就是Java中如何统计List中重复元素的个数的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号