Java 8 new features: Optional, default and static methods in the interface, java8optional

Source: Internet
Author: User

Java 8 new features: Optional, default and static methods in the interface, java8optional
Optional

The Optional class (java. util. Optional) is a container class that indicates that a value exists or does not exist. Originally, null indicates that a value does not exist. Currently, Optional can better express this concept. And avoid NULL pointer exceptions.

Common Methods:

Optional. of (T t): creates an Optional instance.

Optional. empty (): creates an empty Optional instance.

Optional. ofNullable (T t): If t is not null, create an Optional instance. Otherwise, create an empty instance.

IsPresent (): determines whether a value is included.

OrElse (T t): If the called object contains a value, this value is returned; otherwise, t is returned.

OrElseGet (Supplier s): If the call object contains a value, this value is returned; otherwise, the value obtained by s is returned.

Map (Function f): If a value is processed and the Optional after processing is returned, Optional. empty () is returned ().

FlatMap (Function mapper): similar to map, the returned value must be Optional.

The following section references ImportNew to show us how to use Optional correctly. For example, do not write it like this:

public static String getName(User u) {    Optional<User> user = Optional.ofNullable(u);    if (!user.isPresent())        return "Unknown";    return user.get().name;}

This rewrite method is not concise, and its operation is the same as that of the first code. The isPresent method is used instead of u = null. This rewrite is not the correct use of Optional. Let's rewrite it again.

public static String getName(User u) {    return Optional.ofNullable(u)                    .map(user->user.name)                    .orElse("Unknown");}

This is the correct position for using Optional. In this way, we can chain the call with peace of mind, instead of making a layer-by-layer decision. Read a piece of code:

public static String getChampionName(Competition comp) throws IllegalArgumentException {    if (comp != null) {        CompResult result = comp.getResult();        if (result != null) {            User champion = result.getChampion();            if (champion != null) {                return champion.getName();            }        }    }    throw new IllegalArgumentException("The value of param comp isn't available.");}

For various reasons (for example, the competition has not yet won the championship, the abnormal call of methods, the Gift Packs embedded in the implementation of a method, etc.), we are not happy all the way to comp. getResult (). getChampion (). getName () to the end. Other languages, such as kotlin, provide operators at the syntax level: comp ?. GetResult ()?. GetChampion ()?. GetName (). So what should we do in Java!

Let's see what the code will look like after Optional's blessing.

public static String getChampionName(Competition comp) throws IllegalArgumentException {    return Optional.ofNullable(comp)            .map(c->c.getResult())            .map(r->r.getChampion())            .map(u->u.getName())            .orElseThrow(()->new IllegalArgumentException("The value of param comp isn't available."));}

This is quite comfortable. Optional is more attractive than that. Optional also has some magical usage. For example, Optional can be used to check the validity of parameters.

public void setName(String name) throws IllegalArgumentException {    this.name = Optional.ofNullable(name).filter(User::isNameValid)                        .orElseThrow(()->new IllegalArgumentException("Invalid username."));}

The code above references how the importnew-Java8 correctly uses Optional.

Default and static methods in the interface

You can add static methods or default methods to the Java 8 interface. The default methods are modified by default.

public interface Fun<T> {    default void getName(){        System.out.println("hello world");    }    static void getAge(){        System.out.println("nine");    }}

If an interface defines a default method, a parent class of its implementation class defines a method with the same name and parameter list. The method in the parent class is executed when the implementation class is called.

Public class TestF {public void getName () {System. out. println ("TestF") ;}} public interface TestInterface {default void getName () {System. out. println ("hello world") ;}} public class Test extends TestF implements TestInterface {public static void main (String [] args) {Test t = new Test (); t. getName (); // The output is TestF }}

If an implementation class implements two interfaces, if a parent interface provides a default method, the other parent interface also provides a method with the same name and parameter list (regardless of whether the method is the default method), the method must be overwritten to resolve the conflict, otherwise an error will be reported.

Public interface TestInterface {default void getName () {System. err. println ("hello world") ;}} public interface TestInterface1 {void getName ();} public class Test1 implements TestInterface, TestInterface1 {public void getName () {System. out. println ("Tes1F ");}}
Java Learning Group 669823128

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.