In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-13 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
How to analyze the new method of Java9 Optional API, I believe that many inexperienced people do not know what to do about it. Therefore, this paper summarizes the causes and solutions of the problem. Through this article, I hope you can solve this problem.
1. Or method
Sometimes when Optional is empty, we want to execute some other logic and also return Optional. Before Java9, the Optional class had only orElse () and orElseGet () methods, but both returned unwrapped values.
Java9 introduces the or () method to return another Optional when Optional is empty. If Optional has a defined value, the lambda passed into the or method is not executed:
@ Testpublic void givenOptional_whenPresent_thenShouldTakeAValueFromIt () {
/ / given String expected = "properValue"
Optional value = Optional.of (expected)
Optional defaultValue = Optional.of ("default")
/ / when Optional result = value.or (()-> defaultValue)
/ / then assertThat (result.get ()) .isEqualto (expected);}
In addition, when Optional is empty, the return value is also defaultValue:
@ Testpublic void givenOptional_whenEmpty_thenShouldTakeAValueFromOr () {
/ / given String defaultString = "default"
Optional value = Optional.empty ()
Optional defaultValue = Optional.of (defaultString)
/ / when Optional result = value.or (()-> defaultValue)
/ / then assertThat (result.get ()) .isEqualto (defaultString);}
2. IfPresentOrElse method
Suppose there is an instance of Optional, and we usually need to perform a specific business on its wrapped value, and if the Optional instance is empty, we need to add some metrics to record or track this fact.
The ifPresentOrElse () method is created for this scenario. 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 increment a specific counter when the value exists:
@ Testpublic void givenOptional_whenPresent_thenShouldExecuteProperCallback () {
/ / given Optional 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 passed callback parameter is not executed. Let's see how the callback parameter will be executed when Optional is empty:
@ Testpublic void givenOptional_whenNotPresent_thenShouldExecuteProperCallback () {
/ / given Optional 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, the stream () method that Java 9 adds to the Optional class.
Java has a very smooth and elegant Stream Api for manipulating collections to implement functional programming concepts. Java 9 introduces the stream () method into the Optional class, so let's think of the Optional instance as Stream.
Joining us to define an Optional and execute its stream () method creates a flow of elements so that all Api of Stream can be used:
@ Testpublic void givenOptionalOfSome_whenToStream_thenShouldTreatItAsOneElementStream () {
/ / given Optional value = Optional.of ("a")
/ / when List collect = value.stream () .map (String::toUpperCase) .conversation (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:
@ Testpublic void givenOptionalOfNone_whenToStream_thenShouldTreatItAsZeroElementStream () {
/ / given Optional value = Optional.empty ()
/ / when List collect = value.stream () .map (String::toUpperCase) .pictures (Collectors.toList ())
/ then assertThat (collect) .isEmpty ();}
The operation on the empty Stream has no effect, but because of the steam method, we can link Optional api and Stream api to make the code more elegant and smooth.
We introduced three new methods for 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, performs another parameter callback parameter. Finally, the stream () method of Optional provides a stream API for chained operations.
After reading the above, do you know how to analyze the new method of Java9 Optional API? If you want to learn more skills or want to know more about it, you are welcome to follow the industry information channel, thank you for reading!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.