您的位置:首页 > 编程语言 > Java开发

java 求数组中重复元素的个数

2017-06-21 17:03 211 查看
public static void main(String[] args) {
count(new int[]{1, 3, 1, 3,2,4});
}

public static void count(int array[]) {
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for(int a : array) {
map.put(a, map.get(a) == null ? 1 : map.get(a) + 1);
}
for(int key : map.keySet()) {
System.out.println(key + ":" + map.get(key));
}
Arrays.sort(array);


}



用数组元素作为key,然后根据元素key获取,如果null代表没有就存入元素(key) value(个数为1),

如果不为null,就根据元素(key)获取value(个数)加上1
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: