计算ArrayList中的某些元素

时间:2016-03-21 23:45:42

标签: arraylist count element

我想计算ArrayList中包含特定数字的某些元素。

int count = 0;
for (ArrayList a: ArrayLists) {
    if (a.getEverything == 50) {
        count++;
    }
    System.out.println("There are " + count + " people with with this age");

代码问题是它只计算一次,我希望它计算所有50个元素。在我的ArrayList中有4个元素,其中包含50个元素。所以我想要数到4.我怎么能这样做?

2 个答案:

答案 0 :(得分:0)

您的代码似乎很好。假设您有ArrayList<Integer>,而不是循环元素,您还可以使用Collections来计算出现的次数:

ArrayList<Integer> arList = new ArrayList<Integer>();
arList.add(50);
arList.add(50);
arList.add(50);
arList.add(4);
arList.add(4);
System.out.println("No. of occurences of 50: "+Collections.frequency(arList, 50));
System.out.println("No. of occurences of 4: "+Collections.frequency(arList, 4));

答案 1 :(得分:0)

试试这个:

    count = Collections.frequency(a,50);