Java Optional – represents a container object that may or may not contain a non-null value. If the value is present isPresent returns true otherwise false will be returned and the object will be considered empty.

Previously, we wrote about immutable objects, which are also used under the hood of optionals.

Initialize Java 8 Optional

The optional can be initialized using the static constructor as follows:

Optional<String> name = Optional.of("Java");
System.out.println(name); //output line: Optional[Java]

If you put a null value to such a constructor, a java.lang.NullPointerException will occur.

You can use the ofNullable method to safely pass an empty value.

Perfect Java Null Check

In legacy code, you can often see frequent null checks, which clog up the program logic very much. To improve the quality of the code, we recommend using java optional.

Let us look at a simple example:

Optional<String> version = Optional.ofNullable("Java 8");
if (version.isPresent()) {             
   System.out.println(name.get()); //output John
}

In this case, we load a string object with the programming language version. The value can be empty, though.

The isPresent method will return true if the object is not empty, which can help avoid unnecessary NPE exceptions.

For a more advanced version of the code, we can use a lambda expression in the ifPresent method. In this case, the whole check is reduced to a single line.

Optional<String> version = Optional.ofNullable("Java 8");
version.ifPresent(e -> System.out.println(name.get()));

What To Do If The Object Is Empty Or Optional orElse Processing

If the object is empty in the container, you can use the orElse or orElseGet methods

Optional<String> version = Optional.ofNullable("Java 8");
System.out.println(version.orElse("Java 9")); //output Java 8

Optional<Object> empty = Optional.empty();
System.out.println(empty.orElse("Java 9")); //output Java 9

For a more advanced version, you can use lambda expressions again:

Optional<String> version = Optional.ofNullable("Java 8");
System.out.println(version.orElseGet( () -> "Java 9")); //output Java 8

Optional<Object> empty = Optional.empty();
System.out.println(empty.orElseGet(() -> "Java 9")); //output Java 9

Modifying An Object Using Service Stream Methods

map – a method that modifies an object into another object. For example:

String version = repository.findById(versionId)
  .map(version -> version.getCaption()).orElse("Java 8");

filter – makes a selection (filter) from the object you are looking for. For example:

List<User> users = repository.findAll()
  .filter(user -> user.id != 0).orElse(new ArrayList());

flatMap – can convert a specific stream to a new one. For example, a list of lists can be converted into a single list.

Conclusion

Using object containers simplifies the work with frequent checks for empty values. Applying a lambda expression can make the code more elegant and secure.

Hi, I’m Vlad

Leave a Reply

Your email address will not be published. Required fields are marked *