简体   繁体   中英

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> . Each Student have two properties name and Id. I need to check each one of the Student in the list and check each of the two properties. if Both properties and the student object itself are not null then print that student. All using java 8 Optional.

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.

Stream API solution:

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 ):

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'}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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