In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly introduces "how to use Try". In daily operation, I believe many people have doubts about how to use Try. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful for you to answer the doubts about "how to use Try"! Next, please follow the editor to study!
Java's Optional works very well. We generally use Optional for non-empty processing, omitting if processing. The main purpose is to solve the infamous null pointer exception in Java.
For example, we often encounter the non-empty judgment of the input parameters in the usual coding.
Public void getXXX (Map params) {Map map = params; if (map = = params) {map = new HashMap ();}}
As soon as there is more of this kind of code, our program will slowly become shit mountain. At this point, you can use Optional to modify it.
Public void getXXX (Map params) {Map map = Optional.ofNullable (params) .orElse (new HashMap ());}
Fewer lines of code, clear logic, and lower performance:).
1. Complex example
Look at a more complicated example.
If we need a deeper level of data.
String cityCode = customer.getAddress (). GetCity (). GetCityCode (). Substring (0pr 3)
It is unreasonable to get this because one of the rings, which may be empty, will throw a null pointer. Therefore, we need to judge layer by layer.
Public void getCityCode (Customer customer) {String cityCode = "000,000"; if (customer! = null) {Address address = customer.getAddress (); if (null! = address) {City city = address.getCity (); if (city! = null) {String code = city.getCityCode () If (null! = code & & code.length () > = 3) {cityCode = code.substring (0,3);} System.out.println (cityCode);}
Using Optional's lambda syntax, we can change the code to look like this:
Public void getCityCode (Customer customer) {String cityCode = Optional.ofNullable (customer) .map (c-> c.getAddress ()) .map (a-> a.getCity ()) .map (c-> c.getCityCode ()) .filter (s-> s.length () > = 3). Map (s-> s.substring (0) 3) .orElse ("000") }
Is the code good-looking?
Although the appearance is good, the following still needs to point some partial door key content.
2. Secret content of Optional
In fact, guava had similar tools long before Java8 was released (2014), but since there was no lambda syntax at that time, we could only do some simple applications.
Guava's optional supports serialization and can be returned in RPC framework methods, but it is rarely used.
Java's Optional cannot be serialized at all. Why java8's Optional doesn't implement serialization, here's a discussion. Take a look at http://mail.openjdk.java.net/pipermail/jdk8-dev/2013-September/003186.html.
In addition, Java8 has more ifPresent, map, filter, flatMap and orElseThrow methods than Guava. In view of the fact that fewer and fewer people are using Guava Optional, it's okay not to mention it.
Optional will put some pressure on GC. If you develop the underlying framework or use it carefully, netty has been tested and finally abandoned Optional.
But I still like to use it. Who makes the majority of cruder in China?
3. What is Try?
Long-term use of Java-encoded Javaer will have an amazing feeling after seeing languages such as Scala and Kotlin. But these bags are so big that there is a certain cost to introduce them, so they can only be greedy for their bodies.
However, the Java standard library's API support for functional programming is relatively limited. Is there a lightweight way to enhance our Java library? It would be even better if it could be combined with Lambda expressions. Vavr is such a simple Jar package that makes our code write more smoothly.
Its maven coordinates are:
Io.vavr vavr 0.10.3
Here is a great code for sleep sorting:
Public class SleepSort implements Runnable {private int num; public SleepSort (int num) {this.num = num;} @ Override public void run () {try {Thread.sleep (num * 10);} catch (Exception e) {e.printStackTrace ();} System.out.print (num + "") } public static void main (String [] args) {int [] nums = {5, 22, 10, 7, 59, 3, 16, 4, 11, 8, 14, 24, 27, 25, 26, 28, 23, 99}; Arrays.stream (nums) .forEach (n-> new Thread (new SleepSort (n)). Start ();}}
In the Run part, there is so much useless information that we can use Try to modify it.
We can simplify it to the following two lines:
Try.run (()-> Thread.sleep (num*10)) .andThen (()-> System.out.print (num + "))
It supports a lot of methods and can accomplish most of the subsequent business processing. For example, in the onFailure method, log the exception information.
The common handling of jackson json can be simplified to the following code:
String json = Try.of (()-> objectMapper.writeValueAsString (str)) .getOrElse ("{}")
Try is so easy to use. Most importantly, the size of vavr is only more than 800 kb.
4. More operations of vavr
Vavr supports Tuple (tuple), Option, Try, Either, collection convenience, multivariate functions, curring, and so on.
Take a look at the vavr version of if else. Here is the code for the four branches. These strange symbols in it prove that it is only grammatical sugar.
Public String vavrMatch (String input) {return Match (input). Of (Case ($("a"), "A1"), Case ($("b"), "b2"), Case ($("c"), "c3"), Case ($(), "unknown");}
For example, if you want to define a function instead of a class, you can use Function in Java. Unfortunately, Java's Function only supports one parameter.
Using Vavr's Function, a maximum of 22 parameters are supported!
For example, you want to return multiple values in a method. This is easy to implement in python, but you have to define a Class to receive it in Java.
Tuple, you can support the combination of multiple return values. For example, the following code:
/ / (Java, 8) Tuple2 java8 = Tuple.of ("Java", 8); / / "Java" String s = java8._1; / / 8 Integer I = java8._2
Vavr supports returning 8 values at a time.
In addition, there are gadgets such as lazy. Such as delaying access to values.
Lazy lazy = Lazy.of (Math::random); lazy.isEvaluated (); / / = false lazy.get (); / / = 0.123 (random generated) lazy.isEvaluated (); / / = true lazy.get (); / / = 0.123 (memoized)
There are many ways to extend this. But the ones I use most are Try and tuples. It makes the code more elegant and expresses its intentions more clearly.
Oh, right. Resilience4j heavily uses vavr, the officially recommended fuse component after the Hystrix is no longer updated.
At this point, the study on "how to use Try" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
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.