可以使用 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 处理 List<Student> 中的非空 id 属性

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

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