如何找到一个ArrayList相同的整数倍数? [英] How to find multiples of the same integer in an arraylist?

查看:322
本文介绍了如何找到一个ArrayList相同的整数倍数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题如下。我有一个整数的ArrayList。 ArrayList中包含5个整数例如[5,5,3,3,9]或者[2,2,2,2,7]。许多的ArrayList中有重复的值,我不知道该如何计算有多少的每个值的存在。

My problem is as follows. I have an arraylist of integers. The arraylist contains 5 ints e.g[5,5,3,3,9] or perhaps [2,2,2,2,7]. Many of the arraylists have duplicate values and i'm unsure how to count how many of each of the values exist.

问题是如何找到ArrayList中的重复值,并计算有多少特殊的重复有。在第一实施例[5,5,3,3,9]有2 5的和2 3的。 [2,2,2,2,7]的第二个例子是只有4 2的。我希望能够找到所产生的信息,如果有任何重复多少人有什么具体的整数已被复制。

The problem is how to find the duplicate values in the arraylist and count how many of that particular duplicate there are. In the first example [5,5,3,3,9] there are 2 5's and 2 3's. The second example of [2,2,2,2,7] would be only 4 2's. The resulting information i wish to find is if there are any duplicates how many of them there are and what specific integer has been duplicated.

我不太知道如何在Java中做到这一点。

I'm not too sure how to do this in java.

任何帮助将是非常美联社preciated。谢谢你。

Any help would be much appreciated. Thanks.

推荐答案

对于我来说,最直接的答案,将使用 Col​​lections.frequency 方法。沿着这个线的东西:

To me, the most straightforward answer, would be using the Collections.frequency method. Something along the lines of this:

// 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.");
}

如果你愿意,你可以映射每个整数,其出现次数:

If you want to, you could map each Integer with its number of occurrences:

Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (Integer i : noDupes) {
    map.put(i, Collections.frequency(intList, i));
}

这篇关于如何找到一个ArrayList相同的整数倍数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆