0

I am trying to iterate through an ArrayList myWaste, of waste objects.

Some of these waste objects are of type "packaging", from the Packaging class, and the objects of type "packaging" need to be counted, and the count needs to be returned.

I have tried with a for each loop but I am not having much luck:

int count = 0;
for (Waste packaging : myWaste){
    count += 1;
}
return count;
1
  • 1
    Do you mean that Packaging is a class that extends the Waste class? If so, you could just make a for loop iterating through every waste object in your for loop and check if the waste object is an instance of packaging with the instanceof keyword. Commented Mar 28, 2017 at 3:18

2 Answers 2

2

Try this:

int count = 0;
for(myWaste mw : myWaste)
   if(mw instanceof Packaging)
      count++;

Or if you wanna try lambdas with java8+ :

int count = myWaste.stream().filter(myWaste -> myWaste instanceof Packaging).count();
Sign up to request clarification or add additional context in comments.

1 Comment

Since the myWaste ArrayList is consisted of objects that are of the Waste class, can't you use Waste w: myWaste instead of Object o: myWaste?
1

If I'm not mistake, try this:

int count = 0;
for (Waste packaging : myWaste){
    if (packaging instanceof Packaging) {
        count += 1;
    }
}
return count;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.