如何使用 Optional 检查 Java 中集合中模型的所有属性的 Not Null?



假设有一个List<Student>。每个学生有两个属性名称和 ID。我需要检查列表中的每个学生,并检查两个属性中的每一个。如果 S 属性和学生对象本身都不为 null,则打印该学生。全部使用 java 8 可选。

我当然确定没有必要Optional,因为它的用途是通过过滤和映射来处理null值和/或在发生null时提供替代值。

流 API 解决方案:

在这里,java-stream的使用会更合适:

students.stream()                                              // Stream<Student>
.filter(Objects::nonNull)                              // With no null Students
.filter(s -> s.getId() != null && s.getName() != null) // With no null parameters
.forEach(System.out::println);                         // Printed out

尝试以下输入上的代码:

List<Student> students = Arrays.asList(    // only students with id: 1, 2, 4, 6
new Student(1, "a"),               // ... pass the streaming above
null,
new Student(2, "b"),
new Student(3, null),
new Student(4, "d"),
new Student(null, "e"),
new Student(6, "f"));

空对象模式的可选示例:

可选将更适合例如,如果您想下抛空对象(阅读有关该模式的更多信息(:

students.stream()
.map(student -> Optional.ofNullable(student)
.filter(s -> s.getId() != null && s.getName() != null)
.orElse(new NullStudent()))
.forEach(System.out::println);

输出将是:

Student{id=1, name='a'}
NullStudent{}
Student{id=2, name='b'}
NullStudent{}
Student{id=4, name='d'}
NullStudent{}
Student{id=6, name='f'}

最新更新