17370845950

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

在Java中统计List中重复元素的个数,可以通过 Map 来记录每个元素出现的次数。常用的方式是使用 HashMap 遍历List并累加计数。

方法一:使用HashMap手动统计

遍历List,将每个元素作为key,出现次数作为value存入Map。

import java.util.*;

public class CountDuplicates {
    public static Map countElements(List list) {
        Map countMap = new HashMap<>();
        for (String item : list) {
            countMap.put(item, countMap.getOrDefault(item, 0) + 1);
        }
        return countMap;
    }

    public static void main(String[] args) {
        List items = Arrays.asList("apple", "banana", "apple", "orange", "banana", "apple");
        Map result = countElements(items);
        System.out.println(result); // 输出: {orange=1, banana=2, apple=3}
    }
}

方法二:使用Java 8 Stream API

利用 stream()Collectors.groupingBy 可以更简洁地实现统计。

import java.util.*;
import java.util.stream.Collectors;

public class CountWithStream {
    public static Map countElementsWithStream(List list) {
        return list.stream()
                   .collect(Collectors.groupingBy(e -> e, Collectors.counting()));
    }

    public static void main(String[] args) {
        List items = Arrays.asList("apple", "banana", "apple", "orange", "banana", "apple");
        Map result = countElementsWithStream(items);
        System.out.println(result); // 输出: {orange=1, banana=2, apple=3}
    }
}

只获取重复的元素(出现次数大于1)

如果只想知道哪些元素是重复的,可以过滤出计数大于1的项。

Map 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));
基本上就这些,根据需求选择传统方式还是Stream更合适。