简体   繁体   English

如何使用Optional在java中检查集合中模型的所有属性的非空?

[英]How to check Not Null for all the attributes of a Model in a Collection in java using Optional?

Lets say there is a List<Student> .假设有一个List<Student> Each Student have two properties name and Id.每个学生都有两个属性 name 和 Id。 I need to check each one of the Student in the list and check each of the two properties.我需要检查列表中的每个 Student 并检查两个属性中的每一个。 if Both properties and the student object itself are not null then print that student.如果属性和学生对象本身都不为空,则打印该学生。 All using java 8 Optional.全部使用 java 8 可选。

I am certainly sure there is no need of Optional since its usage is to handle null values through filtering and mapping and/or offer an alternative value if null occurs.我当然确定不需要Optional因为它的用法是通过过滤和映射来处理null值和/或在出现null时提供替代值。

Stream API solution:流API解决方案:

Here the usage of would be more suitable:这里使用会更合适:

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

Try the code on the following input:在以下输入上尝试代码:

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"));

Optional example with the null-object pattern:空对象模式的可选示例:

Optional would be more suitable in case you want to for example underthrow a null-object (read more about the pattern ): Optional 会更适合,例如,如果您想抛出一个空对象(阅读有关模式的更多信息):

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

The output would be:输出将是:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM