如何计算ArrayList中的重复元素? [英] How to count duplicate elements in ArrayList?
本文介绍了如何计算ArrayList中的重复元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要分离并统计arraylist中有多少个值是相同的,并根据出现的次数打印出来.
I need to separate and count how many values in arraylist are the same and print them according to the number of occurrences.
我有一个名为 numbers 的数组列表:
I've got an arraylist called digits :
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765]
我创建了一个方法来分隔每个值并将其保存到一个新数组中.
I created a method which separates each value and saves it to a new array.
public static ArrayList<Integer> myNumbers(int z) {
ArrayList<Integer> digits = new ArrayList<Integer>();
String number = String.valueOf(z);
for (int a = 0; a < number.length(); a++) {
int j = Character.digit(number.charAt(a), 10);
digits.add(j);
}
return digits;
}
在此之后,我得到了一个名为 numbers 的新数组.我在这个数组上使用排序
After this I've got a new array called numbers. I'm using sort on this array
Collections.sort(numbers);
我的 ArrayList 看起来像这样:
and my ArrayList looks like this:
[0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 6, 6, 6, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 9, 9, 9]
它有:
2 times 0;
9 times 1;
4 times 2;
6 times 3;
5 times 4;
6 times 5;
5 times 6;
5 times 7;
5 times 8;
3 times 9;
我需要打印出一串数字取决于它们有多少所以它看起来像这样:1354678290
I need to print out the string of numbers depend on how many are they So it suppose to look like this : 1354678290
推荐答案
List<String> list = new ArrayList<String>();
list.add("a");
list.add("b");
list.add("c");
list.add("a");
list.add("a");
list.add("a");
int countA=Collections.frequency(list, "a");
int countB=Collections.frequency(list, "b");
int countC=Collections.frequency(list, "c");
这篇关于如何计算ArrayList中的重复元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文