Moh*_*nde 4 java arrays primitive duplicates
我想检测Java数组中的重复值.例如:
int[] array = { 3, 3, 3, 1, 5, 8, 11, 4, 5 };
Run Code Online (Sandbox Code Playgroud)
我怎样才能获得特定的重复条目以及它出现的次数?
我将Map<Integer, Integer>在第一个整数是value数组中出现的数字,第二个整数是count(出现次数).
array.length在循环中运行map.containsKey(array[i]).如果地图中存在数字,则递增该数字(类似于map.put(array[i], map.get(array[i]) + 1).否则,在地图中创建新条目(例如map.put(array[i], 1),看起来像是一个叫做数据结构的工作multiset.
Multiset<Integer> mp = HashMultiset.create();
mp.addAll(Arrays.asList(new Integer[] { 3, 3, 3, 1, 5, 8, 11, 4, 5 }));
Run Code Online (Sandbox Code Playgroud)
标准JDK 6是原始的,不包含multiset.如果您不想重写它,可以使用预先存在的库,如Google Guava库或Apache Commons.
例如,您可以使用Guava库
for (Integer i : mp.elementSet())
System.out.println(i + " is contained " + mp.count(i) + " times.");
Run Code Online (Sandbox Code Playgroud)
这将输出:
1 is contained 1 times.
3 is contained 3 times.
4 is contained 1 times.
5 is contained 2 times.
8 is contained 1 times.
11 is contained 1 times.
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9842 次 |
| 最近记录: |