Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/316.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
获取在Java中具有特定匹配属性的列表中的对象数_Java_Arrays_List_Properties_Count - Fatal编程技术网

获取在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();