这段代码请帮我翻译成java语言:function countDuplicates(arr) { let countMap = new Map(); let duplicates = 0; // 统计每个元素出现的次数 for (let i = 0; i < arr.length; i++) { let key = arr[i]; let count = countMap.get(key) || 0; countMap.set(key, count + 1); } // 统计重复元素的个数 for (let count of countMap.values()) { if (count > 1) { duplicates++; } } return duplicates;}// 示例用法let arr = [1, 2, 3, 2, 4, 3, 5, 4, 6];let duplicates = countDuplicates(arr);console.log(duplicates); // 输出:3
时间: 2023-03-29 20:02:14 浏览: 49
以下是代码的Java翻译:
```
import java.util.HashMap;
import java.util.Map;
public class Main {
public static int countDuplicates(int[] arr) {
Map<Integer, Integer> countMap = new HashMap<>();
int duplicates = 0;
// 统计每个元素出现的次数
for (int i = 0; i < arr.length; i++) {
int key = arr[i];
int count = countMap.getOrDefault(key, 0);
countMap.put(key, count + 1);
}
// 统计重复元素的个数
for (int count : countMap.values()) {
if (count > 1) {
duplicates++;
}
}
return duplicates;
}
public static void main(String[] args) {
int[] arr = {1, 2, 3, 2, 4, 3, 5, 4, 6};
int duplicates = countDuplicates(arr);
System.out.println(duplicates); // 输出:3
}
}
```
阅读全文