简体   繁体   English

如何在Java中为特定类型迭代对象的ArrayList

[英]How to Iterate over an ArrayList of Objects for a specific type in Java

I am trying to iterate through an ArrayList myWaste, of waste objects. 我试图遍历ArrayList myWaste的废物对象。

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. 这些浪费对象中的某些对象是Packaging类中的“包装”类型,需要对“包装”类型的对象进行计数,并且需要返回该计数。

I have tried with a for each loop but I am not having much luck: 我已经尝试过for每个循环,但是运气不好:

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

Try this: 尝试这个:

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

Or if you wanna try lambdas with java8+ : 或者,如果您想尝试使用java8 +的lambdas:

int count = myWaste.stream().filter(myWaste -> myWaste instanceof Packaging).count();

If I'm not mistake, try this: 如果我没有记错,请尝试以下操作:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM