Look what I found a good thing? Java Optional, definitely worth learning | Force program

Author | silent king

Source | CSDN blog

Head Figure | paid download from the visual China

Exhibition | CSDN (ID: CSDNnews)

Want to learn, never too late, especially for Java 8 inside a good thing, Optional is one of them, which provides a solution for representing the class level optional value rather than a null reference. As a Java programmer, I was really tired NullPointerException (NPE), and although it was cooked like an old friend, know that it is forced - the program is using an object they found this object is null , so the Java virtual machine to bristle to throw it out as a scapegoat.

Of course, we are full of programmers responsible, we will not sit idly by, so there will be a large number of null value checks. Although in some cases this examination was not necessary, but we have become accustomed to the routine. Finally, Java 8 could not stand, on the introduction of the Optional, so that our code is no longer so mean dull.

Optional did not have any problems

We have to simulate a practical application scenario. Wang first day on the job, leading the horse gave him arrange a task, asking him to take a member's name from the database according to pull the member ID, then the names printed to the console. Although it is new, but the task beat Wang, he spent 10 minutes to write this code:

 1public class WithoutOptionalDemo {
 2    class Member {
 3        private String name;
 4
 5        public String getName() {
 6            return name;
 7        }
 8
 9        public void setName(String name) {
10            this.name = name;
11        }
12    }
13
14    public static void main(String[] args) {
15        Member mem = getMemberByIdFromDB();
16        if (mem != null) {
17            System.out.println(mem.getName());
18        }
19    }
20
21    public static Member getMemberByIdFromDB() {
22        // 当前 ID 的会员不存在
23        return null;
24    }
25}

Due to the current member ID does not exist, so getMemberByIdFromDB () method returns a null as a result did not get to the member, it means first sentence of mem empty at the time of printing the names of members, otherwise it will throw an exception NPE ,Do not believe? Wang to make if (mem! = Null) try to remove the console immediately print the error stack to give you some color to see.

1Exception in thread "main" java.lang.NullPointerException
2    at com.cmower.dzone.optional.WithoutOptionalDemo.main(WithoutOptionalDemo.java:24)

How to solve this problem is Optional

After Wang submit the code, then happily go horse to a new task. In the open-minded attitude of learning, Wang horse look request your own code, so Pharaoh told him he should try Optional, to avoid unnecessary null value checks. Now, let's look at Wang is how to solve the problem through the Optional.

 1public class OptionalDemo {
 2    public static void main(String[] args) {
 3        Optional<Member> optional = getMemberByIdFromDB();
 4        optional.ifPresent(mem -> {
 5            System.out.println("会员姓名是:" + mem.getName());
 6        });
 7    }
 8
 9    public static Optional<Member> getMemberByIdFromDB() {
10        boolean hasName = true;
11        if (hasName) {
12            return Optional.of(new Member("沉默王二"));
13        }
14        return Optional.empty();
15    }
16}
17class Member {
18    private String name;
19
20    public String getName() {
21        return name;
22    }
23
24    // getter / setter
25}

getMemberByIdFromDB () method returns Optional <Member> As a result, so it indicates Member may exist or may not exist, this time can be used in ifPresent Optional Lambda expressions () method to print the results directly.

Optional reason can solve the problem of NPE, because it clearly tells us that it does not need to be sentenced empty. It is like the crossroads of road signs clearly tell you where to go.

Creating Optional objects

1) You can use the static method empty () creates an empty object is Optional

1Optional<String> empty = Optional.empty();
2System.out.println(empty); // 输出:Optional.empty

2) Use the static method of () to create a non-empty Optional objects

1Optional<String> opt = Optional.of("沉默王二");
2System.out.println(opt); // 输出:Optional[沉默王二]

Of course, of parameters passed to the () method must be non-empty, that can not be null, otherwise it still throws NullPointerException.

1String name = null;
2Optional<String> optnull = Optional.of(name);

3) Use the static method ofNullable () to create a non-empty space but also an object of the Optional

1String name = null;
2Optional<String> optOrNull = Optional.ofNullable(name);
3System.out.println(optOrNull); // 输出:Optional.empty

Internal ofNullable () method has a triple expression, if the parameter is null, private constant returns EMPTY; otherwise, use new keyword to create a new Optional subject - no longer throws an exception of NPE.

Determined value is present

The method can isPresent () determines whether an object exists Optional, if present, the method returns true, otherwise false-- substituted obj! = Null is determined.

1Optional<String> opt = Optional.of("沉默王二");
2System.out.println(opt.isPresent()); // 输出:true
3
4Optional<String> optOrNull = Optional.ofNullable(null);
5System.out.println(opt.isPresent()); // 输出:false

Java method after 11 can also isEmpty () is determined with isPresent () opposite result.

1Optional<String> opt = Optional.of("沉默王二");
2System.out.println(opt.isPresent()); // 输出:false
3
4Optional<String> optOrNull = Optional.ofNullable(null);
5System.out.println(opt.isPresent()); // 输出:true

Non-NULL expression

Optional class has a very modern way --ifPresent (), allowing the way we use functional programming execute some code, so I call it a non-empty expressions. Without this method, we generally first method Optional object sentenced empty after the implementation of the corresponding code via isPresent ():

1Optional<String> optOrNull = Optional.ofNullable(null);
2if (optOrNull.isPresent()) {
3    System.out.println(optOrNull.get().length());
4}

With ifPresent () later, the situation is completely different, Lambda expressions can be directly passed to the method, the code is more concise, more intuitive.

1Optional<String> opt = Optional.of("沉默王二");
2opt.ifPresent(str -> System.out.println(str.length()));

After 9 Java can ifPresentOrElse (action, emptyAction) perform two results, it executes action is not empty, empty emptyAction performed by the method.

1Optional<String> opt = Optional.of("沉默王二");
2opt.ifPresentOrElse(str -> System.out.println(str.length()), () -> System.out.println("为空"));

Set (get) the default values

Sometimes, we have created (acquired) Optional object, the need for a default value, orElse () and orElseGet () method comes in handy.

orElse () method returns the value Optional wrapped object, if the value is not null, then; otherwise, returns the default value. The method parameter types and worth of the same type.

1String nullName = null;
2String name = Optional.ofNullable(nullName).orElse("沉默王二");
3System.out.println(name); // 输出:沉默王二

orElseGet () method orElse () method is similar to, but with different parameter types. Optional If the object is null, the function parameters is performed.

1String nullName = null;
2String name = Optional.ofNullable(nullName).orElseGet(()->"沉默王二");
3System.out.println(name); // 输出:沉默王二

The output from the form and code point of view, these two methods are very similar, which can not help but arouse our suspicion, Java library designers is necessary to do it?

Suppose now that there is such a way to get the default value, a very traditional way.

1public static String getDefaultValue() {
2    System.out.println("getDefaultValue");
3    return "沉默王二";
4}

Then, orElse () method and orElseGet () method call, respectively getDefaultValue () method to return the default value.

1public static void main(String[] args) {
2    String name = null;
3    System.out.println("orElse");
4    String name2 = Optional.ofNullable(name).orElse(getDefaultValue());
5
6    System.out.println("orElseGet");
7    String name3 = Optional.ofNullable(name).orElseGet(OrElseOptionalDemo::getDefaultValue);
8}

Note: The name is the class name :: method syntax introduced in Java 8, followed by the method name is not (), indicating that this method will not necessarily be called.

The output is shown below:

1orElse
2getDefaultValue
3
4orElseGet
5getDefaultValue

Output is similar, not much different from that in the case of the null value Optional object. If the value Optional object is not null it?

1public static void main(String[] args) {
2    String name = "沉默王三";
3    System.out.println("orElse");
4    String name2 = Optional.ofNullable(name).orElse(getDefaultValue());
5
6    System.out.println("orElseGet");
7    String name3 = Optional.ofNullable(name).orElseGet(OrElseOptionalDemo::getDefaultValue);
8}

The output is shown below:

1orElse
2getDefaultValue
3orElseGet

Hey, orElseGet () call did not go getDefaultValue (). Which method is better performance, you get the point?

Get the value

From intuitive semantic point of view, GET () method is the most authentic Optional object value acquisition method, but unfortunately, the process is flawed, because if Optional object is null, the method throws exception NoSuchElementException. This is completely contrary to our original intention to use Optional classes.

1public class GetOptionalDemo {
2    public static void main(String[] args) {
3        String name = null;
4        Optional<String> optOrNull = Optional.ofNullable(name);
5        System.out.println(optOrNull.get());
6    }
7}

This program will throw an exception at runtime:

1Exception in thread "main" java.util.NoSuchElementException: No value present
2    at java.base/java.util.Optional.get(Optional.java:141)
3    at com.cmower.dzone.optional.GetOptionalDemo.main(GetOptionalDemo.java:9)

Although an exception is thrown NoSuchElementException instead of NPE, but in our view, is clearly in the "kettle black." We recommend orElseGet () method to get the value Optional object.

Filtration values

Wang prior to the code upgrade through Optional classes, and later completed happily talk to the horse to the task. Nag think this guy is good, quick mind, and work actively, it is worth cultivating, and again handed over to Wang a new mission: to check the length of the password when the user registration.

After Wang got the task, delighted, because he was about to learn filter Optional class () method, which came in handy.

1public class FilterOptionalDemo {
2    public static void main(String[] args) {
3        String password = "12345";
4        Optional<String> opt = Optional.ofNullable(password);
5        System.out.println(opt.filter(pwd -> pwd.length() > 6).isPresent());
6    }
7}

Parameter type filter () method is Predicate (Java 8 a new interface function), that is a Lambda expressions may be passed to this method as a condition, if the expression evaluates to false, then a return is EMPTY Optional objects, or objects Optional return after filtration.

In the above example, since the password length is 5, the output results of the program to false. Suppose the length of the password is required between 6-10, then a condition may be further added. Wang look to increase the difficulty of code.

1Predicate<String> len6 = pwd -> pwd.length() > 6;
2Predicate<String> len10 = pwd -> pwd.length() < 10;
3
4password = "1234567";
5opt = Optional.ofNullable(password);
6boolean result = opt.filter(len6.and(len10)).isPresent();
7System.out.println(result);

The results of this program output is true, because the password into a 7, between 6-10. Imagine if Amy using if-else to accomplish this task, the more lengthy codes.

Conversion value

After checking, password length Wang, still feel that not enough fun, feel the need to also check the strength of passwords, such as password can not be "password", this password is weak. So he began to study the map () method, which can follow certain rules to convert existing Optional Optional object to a new object original Optional objects do not change.

First look at a simple example Wang wrote:

 1public class OptionalMapDemo {
 2    public static void main(String[] args) {
 3        String name = "沉默王二";
 4        Optional<String> nameOptional = Optional.of(name);
 5        Optional<Integer> intOpt = nameOptional
 6                .map(String::length);
 7
 8        System.out.println( intOpt.orElse(0));
 9    }
10}

In the above example, Map () method parameters String :: length, means that you are the original string type Optional Optional regenerate a new object according to string length, the type Integer.

Clear the map () method of the basic usage, Wang decided to map () method with the filter () combined with the former for the password into the lower case, which is used to determine the length and whether "password" .

 1public class OptionalMapFilterDemo {
 2    public static void main(String[] args) {
 3        String password = "password";
 4        Optional<String>  opt = Optional.ofNullable(password);
 5
 6        Predicate<String> len6 = pwd -> pwd.length() > 6;
 7        Predicate<String> len10 = pwd -> pwd.length() < 10;
 8        Predicate<String> eq = pwd -> pwd.equals("password");
 9
10        boolean result = opt.map(String::toLowerCase).filter(len6.and(len10 ).and(eq)).isPresent();
11        System.out.println(result);
12    }
13}

Well, my dear readers, that's the entire content of this article - arguably the best ever Optional guide, and can be seen here are the best programmers, brother to have to thumbs you point a praise.

Original link:

https://blog.csdn.net/qing_gee/article/details/104767082

Recommended Reading 

down trend resumption of work, telecommuting technology companies can only "sit still" do?

US group a decade, the world's largest takeaway how to support the delivery of one-stop machine-learning platform is to Make?

Tencent combined ACNet mention fine-grained classification, the effect is up to the latest SOTA | CVPR 2020

My favorite cloud IDE recommendation!

advanced features Solidity written contract of intelligence

return E staff to return to work readme: back to work, Wuhan, Hefei fly first, then go back and pick chartered by the company

You look at every point, I seriously as a favorite

Released 1830 original articles · won praise 40000 + · Views 16,540,000 +

Guess you like

Origin blog.csdn.net/csdnnews/article/details/104890439