Sitemap

Java8: Optional Class

2 min readMar 13, 2021

--

Optional class is a Java8 introduction to ease null handling. This is a wrapper class that can be used with object(not with primitives).

Press enter or click to view image in full size
Photo by Irving Trejo on Unsplash
print(Optional.ofNullable(30));
print(Optional.ofNullable(null));

Let’s see how this method call will print the result.

private static void print(Optional<Integer> i) {
i.ifPresent(System.out::println);}

This method will only print if the value is not null. so out put will be 30 only.

private static void print(Optional<Integer> i) {
System.out.println(i.orElse(300));}

This method will print a default value of 300 if the given value is null, so output will be 30 and 300.

private static void print(Optional<Integer> i) {
System.out.println( i.orElseGet(()-> 400));}

This method will call another method when the value is null. So out put will be 30 & 400.

private static void print(Optional<Integer> i) {
if(i.isPresent()) // prints if not null
System.out.println(i.get());
}

This method will print if the method is not null, so out put would be 30 only.

Java 9 Update

With Streams,

List<String> mylist=sourceList.stream()
.flatMap(Optional::stream)
.collect(Collectors.toList());

Let’s say you have a list with null values (sourceList). You can ignore null values like this

.flatMap(Optional::stream)

Out put of {q,f, ,r, ,w } will be {q,f,r,w} empty values are ignored from the stream.

Or Method

This method will give you a default value when the output is null.

Optional<String> op1=Optional.empty();
System.out.println(op1.get().toString());

Above code will give you a null value as we passing in a empty value. If we add below or method it will output a default value when the original value is null.

Optional<String> op1=Optional.empty();
op1=op1.or(() -> Optional.of("Not Present" ));
System.out.println(op1.get().toString());

ifPresentOrElse Method

This will allow you to pass two implementations based to handle null and non null values.

Optional<Integer> op=Optional.of(1);
op.ifPresentOrElse(integer -> System.out.println(integer), ()-> System.out.println("Not present"));

If you set op to a null value op=Optional.empty(); and test it again it will you will see the “Not present” is printed.

Get Nuwan Zen’s stories in your inbox

Join Medium for free to get updates from this writer.

Read my other blogs:

--

--

Nuwan Zen
Nuwan Zen