Upgrading to Java 8--Chapter III Optional and Similar Classes

Source: Internet
Author: User

Java programmers have been dealing with null pointer anomalies for years. There will be new ways to deal with them in Java8. By wrapping a potentially nullable class called Optianal.

The Optional, optionalint, Optionallong, and optionaldouble classes were added to the Java8 to handle null pointer exceptions ( Nullpointerexceptions).

In Java.util's package, there are many example classes that are referenced using lambda expressions and methods.

These four classes are very similar, optional is the most important of them because he can be used on any type, the other classes can only be used on Integer,long and double.

Optional is a container that contains values that may be null. You should realize that attempting to go to a null reference to invoke a method or property can occur with a NullPointerException exception. Handling NULL pointer exceptions is not difficult, but tedious.

Consider the following code, a company will have an office, and then there will be an address. For the sake of simplicity, there are two properties in this address that are streets and cities, all of which may be null. A company may not have an office, an address may not have complete street and city information.

classCompany {PrivateString name; PrivateOffice Office;  PublicCompany (String name, office office) { This. Name =name;  This. Office =Office; }     PublicString GetName () {returnname; }     PublicOffice Getoffice () {returnOffice; }}classOffice {PrivateString ID; Privateaddress address;  PublicOffice (String ID, address address) { This. ID =ID;  This. Address =address; }     PublicString getId () {returnID; }     PublicAddress getaddress () {returnaddress; }}classAddress {PrivateString Street; PrivateString City;  PublicAddress (String Street, String city) { This. Street =Street;  This. City =City ; }     PublicString Getstreet () {returnStreet; }     PublicString getcity () {returnCity ; }} Public classOptionalDemo1 { Public Static voidMain (string[] args) {Address Address1=NewAddress (NULL, "New York"); Office Office1=NewOffice ("OF1", Address1); Company Company1=NewCompany ("Door never Closed", Office1); //What is the street address of Company1? //In which city Company1 is located?String streetaddress =NULL; String City=NULL; if(Company1! =NULL) {Office Office=Company1.getoffice (); if(Office! =NULL) {Address address=office.getaddress (); if(Address! =NULL) {streetaddress=Address.getstreet (); City=address.getcity (); }}} System.out.println ("Street Name:" +streetaddress); System.out.println ("City:" +City ); }}

OptionalDemo1 class to test the creation of the company instance to get the corporate street address, considering that all properties may be empty, we do a non-empty processing before calling the method, just like the following code:

if NULL ) {            = company1.getoffice ();             if NULL ) {                = office.getaddress ();                 if NULL ) {                    = address.getstreet ();                     = address.getcity ();}}         }

This kind of code is boring and suffers from reading.
This time optional can help you, if you decide to use it, you need to wrap all possible null properties in optional. For example, the Office property in the company class should look like this:

private Optional<Office> office;

The city property in the address class should look like this:

 private Optional<String> city;

Before overriding the above code, look at some of the methods of the optional class:

Method Describe
Empty Returns an empty optional class
Filter If a value exists and is available to match the given Prdicate interface, the value described by Optiaonal is returned, otherwise an empty optional class is returned
FlatMap If the value exists, apply the specified mapping method to the value, return the mapping result of the optional class description, and return an empty optional class if the value does not exist
Get If the value exists, the value is returned; otherwise, a nosuchelementexception exception is thrown.
Ifpresent If the value exists, call the specified consumer interface with this value.
IsPresent Returns True if the value exists, otherwise false.
Map If the value exists, apply the specified mapping method to it. Returns the description result of a optional class if the result is not NULL.
Of Returns a non-null value that is described by a optional.
Ofnullable If the given value is not NULL, returns the value described by optional and, if NULL, returns an empty optional class.
OrElse Returns the value if the value exists, otherwise the specified value is returned.

  

These methods are easy to use, wrap a value in the optional class, call its static method or or ornullable. If you are sure that the value you wrap is not NULL, use the of method. Use the Ofnullable method if the value may potentially exist null. Accordingly, the empty static method returns an empty optional class, for example, a optional class with no value.

The rest of the way is to deal with the optional. If you want to simply retrieve a value in optional, first check if a value exists, you can use the Ispresent method and then use the Get method.

if (Optional.ispresent ()) {    = optional.get ();}

However, this is similar to the case where NULL is not optional handled, but this is a better approach.
The Ifpresent method receives a consumer function interface that is called if the value exists, so if you want to print the value simply, you can:

optional.ifPresent(System.out::println);

If the value exists, nothing will happen.

The Flatmapfang method applies a mapping method and returns a value that is described by a optional, more than that, which can be called by cascading, as follows to check for a series of NULL cases:

Company1.flatmap (company::getoffice).        FlatMap (office::getaddress).        flatMap (address::getcity)        . Ifpresent (System.out::p rintln);

Now, we use the optional class to rewrite the OptionalDemo2 class.
Optionalint, Optionallong and optionaldouble have a subset of optional methods. They all have empty, ifpresent, isPresent, and a primitive type required. Because the original type cannot be null, there is no ofnullable and get method. Substituted, Optionalint has Getastint method, Optionallong has Getaslong method, Optiaonaldouble has getasdouble method. They have no filter,flatmap and map methods.

Upgrading to Java 8--Chapter III Optional and Similar Classes

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.