Suppose we have a student object, and the Optional wrapper for this student object:
public class Student { private String name; private Integer age; // Full parameter constructor public Student(String name, Integer age) { = name; = age; } public String getName() { return name; } public Integer getAge() { return age; } // toString method @Override public String toString() { return"Student{" + "name='" + name + '\'' + ", age=" + age + '}'; } }
public class OptionalTest { public static void main(String[] args) { Student student = new Student("Bob", 18); Optional<Student> studentOpt = (student); } }
Optional does not simplify the originally tedious null value checking if not used with Lambda. For example:
// Writing method 1if (student == null) { return UNKNOWN_STUDENT; } else { return student; } // Writing method 2if (!()) { return UNKNOWN_STUDENT; } else { return (); }
Only by combining Optional with Lambda can it be truly powerful!
Now, let's compare the differences between Lambda + Optional and traditional Java in Java 8 in the following four common null processing scenarios.
Scenario 1: Execute if not null
// if statementif (student!= null) { (student); } // Optional (::println);
Scenario 2: Return if not null, return if null, return a specific value or throw an exception
// if statementif (student == null) { return UNKNOWN_STUDENT; // or throw an exception} else { return student; } // Optional return (UNKNOWN_STUDENT); return (RuntimeException::new);
Scenario 3: If not null, return, if null, the method is called
// if statementif (student == null) { return UNKNOWN_STUDENT; } else { return generateWithFunction(); } // Optional return (() -> generateWithFunction());
Scenario 4: Nested null check
// Java 7 if (student!= null) { String name = (); if (name!= null) { return name; } else { return null; } } else { return null; } // Java 8 return (Student::getName).orElse(null);
It can be clearly seen from the above four scenarios that Optional + Lambda allows us to write a lot of if-else code blocks less. Especially Scene 4, the traditional Java writing seems lengthy and difficult to understand, while Optional+Lambda is concise and clear, clear and easy to understand.
Summarize
By combining Lambda expressions and Optional, Java's null processing becomes more elegant and concise. Hope this article helps you better understand and use these features.
This is the end of this article about a brief analysis of how to handle null values in Java. For more related content on Java processing null values, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!