使用 HashMap 存储元素和对应出现次数;使用 Arrays.sort() 和 count() 方法先排序后计算相邻相同元素个数。
如何判断数组中相同元素的个数
在 Java 中,判断数组中相同元素的个数可以使用以下方法:
1. 使用 HashMap
原理:使用 HashMap 存储数组中的元素和其对应的出现次数。
步骤:
- 创建 HashMap 类型的 HashMap。
-
遍历数组,对于每个元素:
- 如果元素已在 HashMap 中,则将相应的计数器加 1。
- 如果元素不在 HashMap 中,则将其添加到 HashMap,并将计数器设置为 1。
- 最后,HashMap 中的每个 对表示数组中该元素的出现次数。
2. 使用 Arrays.sort() 和 count() 方法
原理:先对数组排序,然后使用 count() 方法计算相邻相同元素的个数。
步骤:
- 使用 Arrays.sort() 方法将数组排序。
- 遍历排序后的数组,对于每个元素,检查其是否与前一个元素相同。如果相同,则将计数器加 1。
- 返回计数器。
示例代码(使用 HashMap):
import java.util.HashMap;
public class SameElementCount {
public static HashMap countSameElements(int[] arr) {
HashMap elementCount = new HashMap<>();
for (int element : arr) {
if (elementCount.containsKey(element)) {

elementCount.put(element, elementCount.get(element) + 1);
} else {
elementCount.put(element, 1);
}
}
return elementCount;
}
public static void main(String[] args) {
int[] arr = {2, 3, 1, 1, 2, 5, 3, 1};
HashMap elementCount = countSameElements(arr);
System.out.println(elementCount);
}
} 示例输出:
{2=2, 3=2, 1=3, 5=1}









![如何从 Go 的 map[string]](http://public-space.oss-cn-hongkong.aliyucs.com/gz/470.jpg)