我的问题如下。我有一个整数数组列表。arraylist包含5个整数,例如[5,5,3,3,9]或也许[2,2,2,2,7]。许多arraylist都有重复的值,我不确定如何计算每个值中有多少。
问题是如何在arraylist中查找重复值并计算该特定重复中有多少。在第一个示例[5,5,3,3,9]中有2个5和2 3个。[2,2,2,2,7]的第二个示例仅为4 2。我希望找到的结果信息是,是否存在重复项,其中有多少重复项,以及已重复了哪个特定整数。
我不太确定如何在Java中执行此操作。
任何帮助将非常感激。谢谢。
对我来说,最直接的答案就是使用该Collections.frequency
方法。与此类似:
// Example ArrayList with Integer values
ArrayList<Integer> intList = new ArrayList<Integer>();
intList.add(2);
intList.add(2);
intList.add(2);
intList.add(2);
intList.add(7);
Set<Integer> noDupes = new HashSet<Integer>();
noDupes.addAll(intList); // Remove duplicates
for (Integer i : noDupes) {
int occurrences = Collections.frequency(intList, i);
System.out.println(i + " occurs " + occurrences + " times.");
}
如果需要,可以将每个Integer
事件及其出现次数进行映射:
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (Integer i : noDupes) {
map.put(i, Collections.frequency(intList, i));
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句