How to Use Optional Type in Java 8 ?

1. Correct Way to Use Optional

Consider the following example:

List<String> list = new ArrayList<String>();
list.add("java");
list.add("php");
list.add("python");
list.add("perl");
list.add("c");
list.add("lisp");
list.add("c#");
Stream<String> wordStream = list.stream();
 
Stream<Integer> lengthStream = wordStream.map(s -> s.length());
Optional<Integer> sum = lengthStream.reduce((x, y) -> x + y);
System.out.println(sum.get());

This is not correct, as there is no null checking.

Instead of using the get() method, do the following:

Optional<Integer> sum = lengthStream.reduce((x, y) -> x + y);
sum.ifPresent(System.out::println);

If a default value is required for the optional object, use sum.orElse(0), or invoke another function to get default value

sum.orElseGet(getValueMethod());

2. Create Optional Values

We can also write methods that return optional objects. To create optional objects, we can either use Optional.of() or Optional.empty().

public static Optional<Integer> sum(int[] arr){
	return arr==null ? Optional.empty() : Optional.of(...computer sum...);
}

Leave a Comment