Java使用stream根据其中两个条件找出一个List对象的条数
可以使用Java的Stream API来实现根据两个条件找出List对象的条数。下面是一个示例代码:
import java.util.Arrays;
import java.util.List;
public class Main {
    public static void main(String[] args) {
        List<Person> persons = Arrays.asList(
                new Person("John", 25),
                new Person("Jane", 30),
                new Person("Alice", 35),
                new Person("Bob", 40)
        );
        long count = persons.stream()
                .filter(person -> person.getAge() > 30 && person.getAge() < 40)
                .count();
        System.out.println("Count: " + count);
    }
    static class Person {
        private String name;
        private int age;
        public Person(String name, int age) {
            this.name = name;
            this.age = age;
        }
        public String getName() {
            return name;
        }
        public int getAge() {
            return age;
        }
    }
}
在上面的代码中,我们定义了一个Person类,包含name和age属性。然后我们创建了一个包含Person对象的List。使用Stream API的filter方法对List进行筛选,只保留满足条件(age大于30且小于40)的Person对象。最后使用count方法来计算满足条件的Person对象的数量
原文地址: https://www.cveoy.top/t/topic/iqc2 著作权归作者所有。请勿转载和采集!