Analysis on new methods of Java 9 optional API
This article introduces the new methods of Java 9 optional API. In addition to modularity, Java 9 also adds three methods to the optional class.
1. Or method
Sometimes when optional is empty, we want to perform some other logic and return optional as well. Before Java 9, the optional class had only orelse () and orelseget () methods, but both returned unpackaged values.
Java 9 introduces the or () method to return another option when the option is empty. If optional has a defined value, the lambda passed into the or method will not be executed:
@Test public void givenOptional_whenPresent_thenShouldTakeAValueFromIt() { //given String expected = "properValue"; Optional<String> value = Optional.of(expected); Optional<String> defaultValue = Optional.of("default"); //when Optional<String> result = value.or(() -> defaultValue); //then assertThat(result.get()).isEqualTo(expected); }
In addition, when optional is empty, the return value is also DefaultValue:
@Test public void givenOptional_whenEmpty_thenShouldTakeAValueFromOr() { // given String defaultString = "default"; Optional<String> value = Optional.empty(); Optional<String> defaultValue = Optional.of(defaultString); // when Optional<String> result = value.or(() -> defaultValue); // then assertThat(result.get()).isEqualTo(defaultString); }
2. Ifpresentoelse method
Suppose there is an optional instance, we usually need to perform specific business on its wrapped value. At the same time, if the optional instance is empty, we need to add some metrics to record or track the fact.
The ifpresentoelse () method is created for this scenario. We can pass in a consumer to execute when the option exists, and runnable to execute when the option is empty.
In the following example, optional exists, and we need to increase a specific counter when the value exists:
@Test public void givenOptional_whenPresent_thenShouldExecuteProperCallback() { // given Optional<String> value = Optional.of("properValue"); AtomicInteger successCounter = new AtomicInteger(0); AtomicInteger onEmptyOptionalCounter = new AtomicInteger(0); // when value.ifPresentOrElse( v -> successCounter.incrementAndGet(),onEmptyOptionalCounter::incrementAndGet); // then assertThat(successCounter.get()).isEqualTo(1); assertThat(onEmptyOptionalCounter.get()).isEqualTo(0); }
Note that the callback parameter passed in is not executed. Let's see how the callback parameter will be executed when optional is empty:
@Test public void givenOptional_whenNotPresent_thenShouldExecuteProperCallback() { // given Optional<String> value = Optional.empty(); AtomicInteger successCounter = new AtomicInteger(0); AtomicInteger onEmptyOptionalCounter = new AtomicInteger(0); // when value.ifPresentOrElse( v -> successCounter.incrementAndGet(),onEmptyOptionalCounter::incrementAndGet); // then assertThat(successCounter.get()).isEqualTo(0); assertThat(onEmptyOptionalCounter.get()).isEqualTo(1); }
3. Stream method
The last method is the stream () method added by Java 9 to the optional class.
Java has a very smooth and elegant stream API, which is used to operate collections to realize the concept of functional programming. Java 9 introduces the stream () method into the optional class. Let's treat the optional instance as a stream.
If we define an optional and execute its stream () method, we will create a stream of elements so that all APIs of the stream can be used:
@Test public void givenOptionalOfSome_whenToStream_thenShouldTreatItAsOneElementStream() { // given Optional<String> value = Optional.of("a"); // when List<String> collect = value.stream().map(String::toUpperCase).collect(Collectors.toList()); // then assertThat(collect).hasSameElementsAs(List.of("A")); }
In addition, when optional does not exist, calling the stream method returns an empty stream:
@Test public void givenOptionalOfNone_whenToStream_thenShouldTreatItAsZeroElementStream() { // given Optional<String> value = Optional.empty(); // when List<String> collect = value.stream() .map(String::toUpperCase) .collect(Collectors.toList()); // then assertThat(collect).isEmpty(); }
The operation on the empty stream has no effect, but because of the stream method, we can link the optional API and stream API to make the code more elegant and smooth.
In this article, we introduced three new methods of Java 9 optional API. The or method returns an optional object when optional is null. Ifpresentoelse() executes the consumer parameter when the value exists, and another parameter callback parameter on the contrary. Finally, the optional stream () method provides a stream API to implement chained operations.
summary
The above is the new method of Java 9 optional API introduced by Xiaobian. I hope it will be helpful to you. If you have any questions, please leave me a message and Xiaobian will reply to you in time. Thank you very much for your support to our website! If you think this article is helpful to you, welcome to reprint, please indicate the source, thank you!