https://grokonez.com/java/java-9/java-9-optional-improvements
Java 9 Optional Improvements
Java 9 Optional comes with some small useful improvements. In this tutorial, we're gonna look at new added methods: stream()
, ifPresentOrElse()
and or()
.
I. New Optional API
1. stream()
With Java 8, this is a way for getting a List of Values from a Stream of Optionals:
List<String> strings = streamOptional()
.map(Optional::get)
.collect(Collectors.toList());
But, if streamOptional()
returns a Stream that contains an empty Optional instance. It will throw a java.util.NoSuchElementException
.
To handle this case, we can add filter()
method:
// streamOptional(): [(Optional.empty(), Optional.of("one"), Optional.of("two"), Optional.of("three")]
List<String> strings = streamOptional()
.filter(Optional::isPresent)
.map(Optional::get)
.collect(Collectors.toList());
// Result: strings[one, two, three]
Java 9 provides new Optional::stream
to work on Optional
objects lazily, it returns a stream of either zero or one/more elements. It also checks empty element automatically and removes it.
// streamOptional(): [(Optional.empty(), Optional.of("one"), Optional.of("two"), Optional.of("three")]
List<String> newStrings = streamOptional()
.flatMap(Optional::stream)
.collect(Collectors.toList());
// Result: newStrings[one, two, three]
2. ifPresentOrElse()
Java 8 Optional provides ifPresent()
method to perform the given action if a value is present, otherwise do nothing.
More at:
https://grokonez.com/java/java-9/java-9-optional-improvements
Java 9 Optional Improvements
Top comments (0)