可以使用Java 8中的Stream来处理List中的数据。具体实现如下:

List<Student> students = new ArrayList<>(); // 假设students已经被初始化

Optional<Student> optionalStudent = students.stream()
    .filter(student -> student.getId() != null)
    .findFirst();

if (optionalStudent.isPresent()) {
    throw new RuntimeException("集合中有id不为空的Student");
}

上述代码使用Stream的filter()方法来过滤出id不为空的Student,再使用findFirst()方法获取第一个匹配的Student。如果集合中有id不为空的Student,optionalStudent.isPresent()会返回true,进而抛出一个RuntimeException异常。如果集合中所有的Student的id都为空,optionalStudent.isPresent()会返回false,代码不会抛出异常

java stream处理ListStudent students中student有一个属性id若集合中有id不为空的就报错

原文地址: https://www.cveoy.top/t/topic/g6eR 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录