Java数组中相同元素的统计
在Java中,统计数组中相同元素的个数有几种常见方法,以下是几种实现方式:
方法1:使用HashMap
import java.util.HashMap;
import java.util.Map;
public class CountDuplicates {
public static void main(String[] args) {
int[] array = {1, 2, 3, 2, 4, 3, 5, 3, 2};
Map<Integer, Integer> frequencyMap = new HashMap<>();
for (int num : array) {
frequencyMap.put(num, frequencyMap.getOrDefault(num, 0) + 1);
}
// 打印结果
for (Map.Entry<Integer, Integer> entry : frequencyMap.entrySet()) {
System.out.println("元素: " + entry.getKey() + ", 出现次数: " + entry.getValue());
}
}
}
方法2:使用Java 8 Stream API
import java.util.Arrays;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
public class CountDuplicatesStream {
public static void main(String[] args) {
int[] array = {1, 2, 3, 2, 4, 3, 5, 3, 2};
Map<Integer, Long> frequencyMap = Arrays.stream(array)
.boxed()
.collect(Collectors.groupingBy(
Function.identity(),
Collectors.counting()
));
// 打印结果
frequencyMap.forEach((key, value) ->
System.out.println("元素: " + key + ", 出现次数: " + value));
}
}
方法3:使用双重循环(不推荐,效率低)
public class CountDuplicatesNestedLoop {
public static void main(String[] args) {
int[] array = {1, 2, 3, 2, 4, 3, 5, 3, 2};
for (int i = 0; i < array.length; i++) {
int count = 1;
for (int j = i + 1; j < array.length; j++) {
if (array[i] == array[j]) {
count++;
array[j] = -1; // 标记已计数
}
}
if (array[i] != -1) {
System.out.println("元素: " + array[i] + ", 出现次数: " + count);
}
}
}
}
方法4:使用Collections.frequency(适用于对象数组)
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class CountDuplicatesWithFrequency {
public static void main(String[] args) {
Integer[] array = {1, 2, 3, 2, 4, 3, 5, 3, 2};
List<Integer> list = new ArrayList<>(Arrays.asList(array));
for (Integer num : array) {
if (num != null) {
int count = Collections.frequency(list, num);
System.out.println("元素: " + num + ", 出现次数: " + count);
// 移除已统计的元素,避免重复统计
list.removeAll(Collections.singletonList(num));
}
}
}
}
注意事项
- 对于基本类型数组(如int[]),方法1和方法2更高效
- 对于对象数组(如Integer[]),所有方法都适用
- 方法3效率最低(O(n²)),仅适用于小数组
- 如果需要保留原始数组顺序,可以考虑使用LinkedHashMap代替HashMap
选择哪种方法取决于你的具体需求、数组大小和性能要求,对于大多数情况,方法1或方法2是最佳选择。
