Java 8 new features: 4-optional class

Source: Internet
Author: User

Original

First look at the instructions above:

/** * A container object which may or could not contain A non-null value. * If A value is present, {@code isPresent ()} would return {@code true} and * {@code get ()} would return the value. *optional is a container object that may or may not contain a non-null value, and if this value exists, the Ispresent method will return the True,get method will return it itself * <p>additional methods that depend on the presence or absence of a contained * value is provided, such as {@link #orElse (java.lang.Object) OrElse ()}  * (return a default value if value not present) and * {@link #ifPresent (Java.util.function.Consumer) ifpresent ()} (Execute A block * of code if the value is present). *optional provides some additional methods that depend on whether or not the object it contains exists, such as OrElse if the contained object does not exist, a default value and Ifpresent method will be returned, and if the contained value exists, the contents of the method block will be executed * <p >this is a <a href= ". /lang/doc-files/valuebased.html ">value-based</a> * class; Use of identity-sensitive operations (including reference equality * ({@code = =}), hash code, or synchronization) on Inst Ances of * {@code Optional} May has unpredictable results and should be avoided. * This is based on aThe class class of values, for identity-sensitive operations (including referential equality such as = =), identity hashcode or synchronization, etc., to optional instances can produce unpredictable results, which should be avoided. * @since 1.8 * *

  

And look at the class:
Public final class Optional<t>
Here is a final class
This is a value-based class, above gives what is called based on the value, the above given the link address is not full, see here:
Http://docs.oracle.com/javase/8/docs/api/java/lang/doc-files/ValueBased.html

Here is the value-based class that needs to meet the following points:
1. Final type and immutable (may contain references to mutable objects)
2, with Equals, hashcode, the implementation of the ToString method, it is calculated by the state of the instance, and will not be calculated by other objects or variables.
3. Do not use identity-sensitive operations, such as referencing equality, hashcode, or intrinsic locks between two instances.
4, Judge two values equal only through the equal method, but not through = = to judge.
5. It does not provide a construction method, it creates an instance of it through a factory method, which does not guarantee the consistency of the returned instance.
6, when they are equal, it can be freely replaced. If x and Y call the equal method to return True, then x and Y can be exchanged arbitrarily, and its result will not have any change.

And then come back to see optional, and you can see it's private:

Private Optional () {    this.value = null;}

 

In all of its methods, if you want to create a optional object, first look at the three common methods it uses.
The empty method returns a blank optional object.
The of method receives a T parameter, and T must be a non-null value, returning a optional object.
The Ofnullable method receives a T parameter, and if T is null, it calls the empty method, or the by method if it is not null.

Take a look at these two ways:
IsPresent: Returns True if the value of this object is not NULL, otherwise false.
Get: Returns this value if this value is present, or throws an exception if the value is null.
In use, these two methods are basically paired up, and here's an example.

String str = "Hello";optional<string> strvalue = Optional.of (str); System.out.println ("Part1-------------------"); if (str! = null) {   System.out.println (str);} System.out.println ("Part2-------------------"), if (Strvalue.ispresent ()) {   System.out.println (Strvalue.get () );}

Here, the code for Part1 and Part2 is equivalent, and optional provides an easier way
Strvalue.ifpresent (S-System.out.println);
The Ifpresent method receives a consumer function interface (described earlier) and writes its own non-empty logic. Optioanal the method is more concise.

OrElse method: Receives a parameter, if present, returns the value itself, otherwise returns this parameter.
Orelseget method: Receives a supplier, if present, returns the value itself, otherwise returns supplier
Object.

Map method: Receives a function that throws an exception if optioanal is null (so it is recommended to use optional.ofnullable () when creating the optional object), or null if NULL value is returned. Returns the function's return value if it is not empty.
(for example, an object, obj, has a list property, and if list has a value, returns a list, otherwise returns an empty collection, which you can write (

Parent parent = new parent ();optional<parent> Parentval = optional.ofnullable (parent); System.out.println (Parentval.map (M.getlist ()). OrElse (Collections.emptylist ()));

Optioanal is usually used as the return value of a method, it can effectively evade the result of returning null, if a class needs to serialize, when optional as a parameter type or member variable type is problematic. Because optional does not implement serialization, OPTIOANL is not generally recommended as a parameter or constant.

Here are some examples of common optional:

Package Com.demo.jdk8;import Java.util.collections;import Java.util.list;import Java.util.optional;public class      Test6 {public static void main (string[] args) {String str = "Hello";      optional<string> strvalue = Optional.of (str);      System.out.println ("Part1-------------------");      if (str! = null) {System.out.println (str);      } System.out.println ("Part2-------------------");      if (Strvalue.ispresent ()) {System.out.println (Strvalue.get ());      } System.out.println ("Part3-------------------");      Strvalue.ifpresent (S-System.out.println);      System.out.println ("Part4-------------------");      Optional<string> op = optional.ofnullable (null);      System.out.println (Op.orelse ("hahahaha"));      System.out.println ("Part5-------------------");      optional<string> opt = optional.ofnullable ("Nihao");      System.out.println (Op.orelseget ((), "hehehe"));      System.out.println ("Part6-------------------");System.out.println (Opt.map (M-M + "123"). Orelseget ((), "World");        System.out.println ("Part7-------------------");        Parent parent = new parent ();//List<object> List = Arrays.aslist ("Zhang San", "John Doe");//Parent.setlist (List);        optional<parent> parentval = optional.ofnullable (Parent);    System.out.println (Parentval.map (M.getlist ()). OrElse (Collections.emptylist ()));    } public void Test (Optional Optional) {}}class parent{private list<object> List;    Public list<object> getList () {return List;    } public void setlist (list<object> list) {this.list = list; }}

  

For an example, see here: https://github.com/LeeScofield/java8

Java 8 new features: 4-optional class

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.