获取在Java中具有特定匹配属性的列表中的对象数
我有一个这样的动物列表:获取在Java中具有特定匹配属性的列表中的对象数,java,arrays,list,properties,count,Java,Arrays,List,Properties,Count,我有一个这样的动物列表: Animal : int id; boolean carnivore; int leg; 在一个函数中,我想检索,例如,列表中食肉动物的数量(食肉动物是真的) 而不是这样做: Integer nb = 0; for (Animal a : ListAnimal) { if (a.isCarnivore()) { nb++; } } 有更好的方法吗? 谢谢。对
Animal :
int id;
boolean carnivore;
int leg;
在一个函数中,我想检索,例如,列表中食肉动物的数量(食肉动物是真的)
而不是这样做:
Integer nb = 0;
for (Animal a : ListAnimal) {
if (a.isCarnivore()) {
nb++;
}
}
有更好的方法吗?
谢谢。对
nb
变量使用int
,而不是整数
Java8中的另一个版本是
long nb = ListAnimal.stream().filter(Animal::isCarnivore).count();
在java 8中,使用isCarnivore()
方法作为谓词
对列表中的流进行filter()
,然后调用count()
:
在我看来并非如此。你只需要像刚才那样循环检查。我想你不会发现更好的。更好是什么意思?
long nb = ListAnimal.stream().filter(Animal::isCarnivore).count();