Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to count number of instances of specific class in arraylist?

Tags:

java

java-7

I have an array list that looks like:

[new Class1(), new Class2(), new Class1(), new Class1()]

I want to know the most efficient way to extract the number of instances of Class1 in the array list.

For the above example, I want the answer 3.

I am using Java version "1.7.0_79".

like image 876
danday74 Avatar asked Apr 06 '16 04:04

danday74


4 Answers

You could iterate through the ArrayList and check using the instanceof operator.

for (Object e : lst)
{
  if (e instanceof Car)
  {
    carCount++;
  }
}
like image 156
Logan Avatar answered Oct 16 '22 10:10

Logan


if the arraylist is like below,

newClass1 = new Class1();

[newClass1, new Class2(), newClass1, newClass1]

then you can check the frequency like below,

Collections.frequency(arrayList, newClass1);

If you are always adding new instance of Class1 then below will be the solution

[new Class1(), new Class2(), new Class1(), new Class1()]

override equals method in Class1 like below,

 @Override
public boolean equals(Object o){

    if(!(o instanceof Class1 )){
        return false;
    }else{

            return true;
    }
}

then in your test class,

System.out.println(Collections.frequency(array, new Class1()));
like image 42
Raghu Nagaraju Avatar answered Oct 16 '22 11:10

Raghu Nagaraju


You can need to check the class at any given position in the array by using the keyword instanceof

Example:

public static void main(String[] args) {
    Number[] myN = new Number[5];
    
    //populate... ignore this if  want
    for (int i = 0; i < myN.length; i++) {
        if (i%2==0) {
            myN[i]= new Integer(i);
        }else{
            myN[i]= new Double(i);
        }
    }
    int classACounter=0;
    int classBCounter=0;
    //check
    for (int i = 0; i < myN.length; i++) {
        if (myN[i] instanceof Integer){
            System.out.println(" is an int");
            classACounter++;
        }
        if (myN[i] instanceof Double){
            System.out.println(" is a double");
            classBCounter++;
        }
    }
    
    System.out.println("There are "+classACounter+" elements of the class A");
    System.out.println("There are "+classBCounter+" elements of the class B");
}
like image 2
ΦXocę 웃 Пepeúpa ツ Avatar answered Oct 16 '22 09:10

ΦXocę 웃 Пepeúpa ツ


Well, You can easily filter them by

result = Iterables.filter(collection, YourClass.java);

then you can apply .size() on the result.

like image 2
Ducaz035 Avatar answered Oct 16 '22 10:10

Ducaz035