Member-only story
Use Java Optional Fluently
The Optional class contains multiple public methods like filter(), map() and flatMap() which are useful for functional and fluent programming. In this article, we will explore the functional and fluent style of programming using Java Optional.
Check out my YouTube channel where you will see quality and original Java content — https://www.youtube.com/@viraj_shetty
Also check out my discounted Udemy Courses at https://www.mudraservices.com/courses/
Java Optional Basics
Let’s refresh the basics of Java Optional. Below is a simple example of a User Record which has the following data attributes — user id, name, address and whether the user is the CEO. Here’s an example of how Optional class can be used in our code.
// User Record
record User(String uid, String name,
Address address, boolean ceo){
public static final User DEFAULT_USER
= new User("0", "Dummy", null, false);
}
// Address record
record Address(String line, String zip) {
}
// A User Factory class to create User objects
public class Users {
public static Optional<User> getUser(String uid) {
User user = null;
// logic to set user variable
return Optional.ofNullable(user);
}
}
// Calling the getUser method which returns Optional
Optional<User> oUser = Users.getUser(uid);
if…






