Analysis of Java 9 optional API new method

Time:2021-5-1

This paper introduces the new method 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 execute some other logic and return optional as well. Before java9, the optional class had only orelse() and orelseget() methods, but both returned non wrapped values.

Java 9 introduces the or () method to return another option when it is empty. If optional has a defined value, the lambda passed into the or method is not 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. Ifpresentorelse method

Suppose there is an optional instance, we usually need to perform a 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 ifpresentorelse () method is created for this scene. We can pass in a consumer to execute when optional exists, and runnable to execute when optional is empty.

In the following example, optional exists, and we need to increase the 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 incoming callback parameter has not been 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 sets 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, call the stream method to return 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 steam method, we can link the optional API and the stream API to make the code more elegant and fluent.

In this article, we introduce three new methods of Java 9 optional API. The or method returns an optional object when optional is empty. Ifpresentorelse() executes the consumer parameter when the value exists, and vice versa. Finally, optional stream () method provides stream API to realize chain operation.

summary

The above is the new method of Java 9 optional API introduced by Xiaobian. I hope it can help you. If you have any questions, please leave me a message and Xiaobian will reply you in time. Thank you very much for your support to developer!
If you think this article is helpful to you, please reprint, please indicate the source, thank you!

Recommended Today

Large scale distributed storage system: Principle Analysis and architecture practice.pdf

Focus on “Java back end technology stack” Reply to “interview” for full interview information Distributed storage system, which stores data in multiple independent devices. Traditional network storage system uses centralized storage server to store all data. Storage server becomes the bottleneck of system performance and the focus of reliability and security, which can not meet […]