Java 8 Optional class depth parsing

Source: Internet
Author: User
Tags getmessage throwable

Original link: Javacodegeeks translation: importnew.com-Go Junyang
Link: http://www.importnew.com/6675.html

As a Java programmer, you might have the experience of calling a method to get a return value but not invoking the return value directly as a parameter. We will first determine if the return value is null and can be used as a parameter to other methods only if it is not null. This is what some of the external APIs like Guava are trying to solve. Some JVM programming languages, such as Scala, Ceylon, etc., have been addressed in the core API for this issue. In my previous article , I described how Scala solves this problem.

New versions of Java, such as Java 8 , introduce a new Optional class. The Javadoc description of the optional class is as follows:

This is a nullable container object. If the value is present, the Ispresent () method returns True, and the call to the Get () method returns the object.

This article explores the methods that the optional class contains, and shows how to use them through one or two examples.

Of

Creates a optional for a value that is not NULL.

The of method creates the optional class from the factory method. It is important to note that the arguments passed in when the object was created cannot be null. If the incoming parameter is NULL, NullPointerException is thrown.

// Call the factory method to create an optional instance optional<string> name = Optional.of ("Sanaulla"); // The passed-in parameter is NULL, throwing nullpointerexception. optional<string> somenull = Optional.of (null);

Ofnullable

Creates a optional for the specified value, or returns an empty optional if the specified value is null.

Ofnullable is similar to the of method, and the only difference is that you can accept a null argument. Examples are as follows:

// The following creates a optional instance that does not contain any values // For example, the value is ' null ' Optional empty = optional.ofnullable (null);

IsPresent

Very easy to understand

Returns True if the value exists, otherwise false.

Code similar to the following:

// The Ispresent method is used to check if the optional instance contains a value if (Name.ispresent ()) {  // call Get () within the optional instance to return a value that already exists  System.out.println (Name.get ()); // Output Sanaulla}

Get

If the optional has a value, it is returned, or nosuchelementexception is thrown.

In the above example, the Get method is used to get the value in the optional instance. Let's look at an example of a thrown nosuchelementexception:

   try {  // call Get () on an empty optional instance, throw nosuchelementexception  catch ( nosuchelementexception ex) {  System.out.println (ex.getmessage ());}    

Ifpresent

Call consumer If the optional instance has a value, otherwise it will not be processed

To understand the Ifpresent method, you first need to understand the consumer class . Jane replied that the consumer class contains an abstract method. The abstract method processes the passed-in value, but does not return a value. JAVA8 supports passing parameters directly through a lambda expression without an interface.

If the optional instance has a value, calling Ifpresent () can accept either an interface segment or a lambda expression. Code similar to the following:

// The Ifpresent method accepts a lambda expression as a parameter. the //lambda expression Optional The value of the call to consumer for processing. name.ifpresent (value), {  System.out.println ("The length of the value is:" +  Value.length ());});

OrElse

Returns a value if it is available, otherwise returns the other value specified.

If the optional instance has a value, it is returned, otherwise the parameter passed in by the OrElse method is returned. Examples are as follows:

// If the value does not return the value of the optional instance for the Null,orelse method.  // If NULL, returns the incoming message.  // output: There is no value present! System.out.println (Empty.orelse ("There is no value present!" )); // Output: Sanaulla System.out.println (Name.orelse ("There is some value!"));

Orelseget

Orelseget is similar to the OrElse method, except that the default value is obtained. The OrElse method takes the passed-in string as the default value, and the Orelseget method can accept the implementation of the supplier interface to generate the default value. Examples are as follows:

// Orelseget is similar to the OrElse method, except that the default value is OrElse passed in. // Orelseget can accept a lambda expression to generate a default value.  // output: Default valueSystem.out.println (Empty.orelseget ((), "Default value"); // Output: Sanaulla System.out.println (Name.orelseget ((), "Default Value"));

Orelsethrow

If there is a value then return it, or throw the exception created by the supplier interface.

In the Orelseget method, we pass in a supplier interface . However, in Orelsethrow we can pass in a lambda expression or method that throws an exception if the value does not exist. Examples are as follows:

Try {  //Orelsethrow is similar to the OrElse method. Unlike the return default value,  //   empty.orelsethrow (valueabsentexception::New  catch  (Throwable ex) {  // output: No value present in the Optional Instance  System.out.println (Ex.getmessage ());}

Valueabsentexception is defined as follows:

class extends Throwable {   public  valueabsentexception () {    Super();  }     Public valueabsentexception (String msg) {    super(msg);  }   @Override  public  String getMessage () {    return ' No value present in The Optional instance ";  }}

Map

The Map method documentation is described below:

If there is a value, call the mapping function on it to get the return value. If the return value is not NULL, a optional that contains the mapping return value is created as the map method return value, otherwise an empty optional is returned.

The map method is used to perform a series of operations on the value of the optional instance. Through a set of lambda expressions that implement the function interface, the incoming operation. If you are unfamiliar with the function interface, you can refer to my blog post. The Map Method example is as follows:

// The map method executes the passed-in lambda expression parameter to modify the value of the optional instance.  // creates a new optional instance for the return value of the lambda expression as the return value of the map method. optional<string> uppername = Name.map ((value)- value.touppercase ()); System.out.println (Uppername.orelse ("No value found"));

FlatMap

If there is a value, the mapping function for which it is executed returns the optional type return value, otherwise an empty optional is returned. Flatmap is similar to the map (Funtion) method, except that the mapper return value in Flatmap must be optional. At the end of the call, Flatmap does not encapsulate the result in optional.

The Flatmap method is similar to the map method, except that the return value of the mapping function is different. The mapping function return value of the map method can be any type T, and the mapping function of the Flatmap method must be optional.

Referring to the map function, an example of using Flatmap overrides is as follows:

// Flatmap is very similar to map (Function), except that the return type of the lambda expression passed in to the method. ////uppername = Name.flatmap ((value), optional.of ( Value.touppercase ())); System.out.println (Uppername.orelse ("No value found")); // Output Sanaulla

Filter

The filter method filters the value of the optional instance by passing in a qualified condition. The documentation is described below:

Returns an empty optional if there is a value and the assertion condition is met to return the optional that contains the value.

Reading this, you may already know how to pass in a piece of code for the filter method. Yes, you can pass in a lambda expression here. For the filter function, we should pass in a lambda expression that implements the predicate interface. If you are unfamiliar with the predicate interface, you can refer to this article .

Now let me take a look at the various uses of filter, the following example shows that the qualification is satisfied and does not meet two conditions:

 // filter method checks whether a given option value satisfies certain conditions.  //  optional<string> longname = Name.filter ((value) Value.length () > 6 ); System.out.println (Longname.orelse ( "the name is less than 6 characters")); //  output Sanaulla  //  optional<string> anothername = Optional.of ("Sana"  < string> shortname = Anothername.filter ((value) value.length () > 6 //  output: name is less than 6 characters long  System.out.println (Shortname.orelse ("The name is less than 6 characters")); 

Above, we introduce each method of the optional class. The following is a complete example of the use of a centralized display:

 Public classOptionaldemo { Public Static voidMain (string[] args) {//Create a optional instance, or you can return it by means of a method. optional<string> name = Optional.of ("Sanaulla"); //Create an optional instance with no value, for example, a value of ' null 'Optional empty = optional.ofnullable (NULL); //The Ispresent method is used to check whether the optional instance has a value.     if(Name.ispresent ()) {//call Get () to return the optional value. System.out.println (Name.get ()); }     Try {      //call Get () on the optional instance to throw the nosuchelementexception. System.out.println (Empty.get ()); } Catch(Nosuchelementexception ex) {System.out.println (Ex.getmessage ()); }     //The Ifpresent method accepts the lambda expression parameter. //If the optional value is not empty, the lambda expression processes and executes the action on it. Name.ifpresent (value){System.out.println ("The length of the value is:" +value.length ());     }); //if the value OrElse method returns an optional instance, the incoming error message is returned. System.out.println (Empty.orelse ("There is no value present!")); System.out.println (Name.orelse ("There is some value!")); //Orelseget is similar to OrElse, except that the default value is passed in. //Orelseget accepts a lambda expression to generate a default value. System.out.println (Empty.orelseget (), "Default Value")); System.out.println (Name.orelseget ()"Default Value")); Try {      //Orelsethrow is similar to the OrElse method, except that the return value is the difference. //Orelsethrow thrown by an incoming lambda expression/method generates an exception. Empty.orelsethrow (valueabsentexception::New); } Catch(Throwable ex) {System.out.println (Ex.getmessage ()); }     //The Map method modifies the default value of the Optonal instance by passing in the lambda expression. //the lambda expression return value is wrapped as an optional instance. optional<string> uppername = Name.map ((value)value.touppercase ()); System.out.println (Uppername.orelse ("No value found")); //Flatmap is very similar to map (Funtion), except for the return value of a lambda expression. //the lambda expression return value of the map method can be any type, but the return value is wrapped as a optional instance. //However, the lambda return value of the Flatmap method is always optional type. Uppername = Name.flatmap ((value)Optional.of (Value.touppercase ())); System.out.println (Uppername.orelse ("No value found")); //The filter method checks whether the Optiona value satisfies the given condition. //returns an empty optional if the return optional instance value is satisfied. optional<string> longname = Name.filter ((value) Value.length () > 6); System.out.println (Longname.orelse ("The name is less than 6 characters")); //Another example, the optional value does not meet the given criteria. optional<string> anothername = Optional.of ("Sana"); Optional<String> shortname = Anothername.filter ((value), Value.length () > 6); System.out.println (Shortname.orelse ("The name is less than 6 characters")); } }

The above code output is as follows:

8There is no value present!  6 characters

Java 8 Optional class depth parsing

Related Article

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.