jdk8 new features -Optional

Summary

Optional principal problem is the infamous null pointer exception (NullPointerException). It provides a set to a null value (ofNullable), value is present (isPresent), the default value (orElse) is empty or the like, when the operation target let gracefully handle null values.


Examples

1.empty()

Create an empty by empty Optional, will get an error when this time

2.get()

get () method to get Optional value that, if the space-time will be reported java.util.NoSuchElementException: No value present

System.out.println("-----Optional.empty-----");
Optional<String> optional=Optional.empty();
optional.get();

Export

-----Optional.empty-----
java.util.NoSuchElementException: No value present

3.of()

of () Optional filling the value at this time can not be empty, empty error

System.out.println("-----Optional.off-----");
User emptyUser=null;
Optional<User> optional = Optional.of(emptyUser);

Export

-----Optional.off-----
java.lang.NullPointerException

4.ofNullable()

ofNullable () Optional filling the value at this time may be null

System.out.println("-----Optional.ofNullable-----");
User emptyUser=null;
Optional.ofNullable(emptyUser);

5.isPresent()

Optional determined value is present

System.out.println("-----Optional.isPresent-----");
Optional<String> optional= Optional.empty();
 System.out.println(optional.isPresent());

Export

-----Optional.isPresent-----
false

In addition to performing the inspection method, also received a Consumer (consumer) parameter, if the object is not empty, the implementation of incoming Lambda expressions:

System.out.println("-----Optional.isPresentLambda-----");
User user=new User(1,"小杨");
Optional<User> optional= Optional.of(user);
optional.ifPresent( u -> System.out.println("用户名:"+u.getName()));

Export

-----Optional.isPresentLambda-----
用户名:小杨

6.orElse ()

orElse () value if the value is returned, otherwise the value of the parameter passed to it

System.out.println("-----Optional.orElse-----");
User emptyUser=null;
User user=new User(1,"小杨");
User res= Optional.ofNullable(emptyUser).orElse(user);
System.out.println(toString(res));

Export

Optional.orElse ----- -----
{ "ID":. 1, "name": "Yang"}

7.orElseGet ()

When there is a value of the return value, if no value, it performs as a parameter a Supplier (provider) interface function, and returns the execution result.

@Test
public void orElseGet(){
    System.out.println("-----Optional.orElseGet-----");
    User emptyUser=null;
    User res= Optional.ofNullable(emptyUser).orElseGet(()->getDefaultUser());
    System.out.println(toString(res));
}
private User getDefaultUser(){
    System.out.println("创建默认用户");
    User user=new User(0,"管理员");
    return user;
}

Export

----- Optional.orElseGet -----
create a default user
{ "id": 0, " name": " Administrators"}

orElse () and orElseGet () there is no difference in the value of space-time, but will still run orElse orElse created when there is a value () of the object

@Test
public void orElseGetAndOrElse(){
    System.out.println("-----Optional.orElseGetAndOrElse-----");
    User defUser=new User(1,"小杨");
    System.out.println("Optional.orElse");
    User user = Optional.ofNullable(defUser).orElse(getDefaultUser());
    System.out.println(toString(user));
    System.out.println("Optional.orElseGet");
    User res= Optional.ofNullable(defUser).orElseGet(()->getDefaultUser());
    System.out.println(toString(res));
}

private User getDefaultUser(){
    System.out.println("创建默认用户");
    User user=new User(0,"管理员");
    return user;
}

Export

Optional.orElseGetAndOrElse ----- -----
Optional.orElse
create a default user
{ "id": 1, " name": " Yang"}
Optional.orElseGet
{ "id": 1, " name": " Xiao Yang "}

8.orElseThrow()

Object is empty when thrown

System.out.println("-----Optional.orElseThrow-----");
String res = (String)Optional.empty().orElseThrow( () -> new IllegalArgumentException("值为空"));

Export

Optional.orElseThrow ----- -----
java.lang.IllegalArgumentException: is empty

9.map()

Parameter values ​​as a function call, and then returns the value Optional packaging.

System.out.println("-----Optional.map-----");
User user=new User(1,"小杨");
String userName=Optional.ofNullable(user).map(u->u.getName()).get();
System.out.println(userName);

Export

----- Optional.map -----
Xiao Yang

10.filter()

Returns true value of the filtered result. If the test is false, it returns an empty Optional

System.out.println("-----Optional.filter-----");
System.out.println("-----name=小杨-----");
User user=new User(1,"小杨");
String res=Optional.ofNullable(user).filter(u->u.getName().equals("小杨")).map(u->u.getName()).orElse("用户不存在");
System.out.println(toString(res));
System.out.println("-----name=小张-----");
String res1=Optional.ofNullable(user).filter(u->u.getName().equals("小张")).map(u->u.getName()).orElse("用户不存在");
System.out.println(toString(res1));

Export

Optional.filter ----- -----
----- ----- Yang name =
"Yang"
----- ----- Zhang name =
"user does not exist."


Elegant treatment NPE

1. Traditional treatment NPE

private static String defaultPreUrl="http://127.0.0.1/preview/miss.jpg";
private static FileV1 file1=new FileV1(1,"测试文件",null,"http://127.0.0.1/file/test.pdf");
private static ResourceV1 resource1 = new ResourceV1(1,"测试资源",file1);
@Test
public void NPEV1(){
   System.out.println("-----------传统NPE判断-----------");
   String url=defaultPreUrl;
   if (file1 != null) {
       FileV1 file = resource1.getFile();
       if (file != null) {
           PreviewV1 preview = file.getPreview();
           if (preview != null) {
               url = preview.getUrl();
           }
       }
   }
   System.out.println(url);
}
class ResourceV1{
    private Integer id;
    private String name;
    private FileV1 file;
    public ResourceV1(Integer id, String name, FileV1 file) {
        this.id = id;
        this.name = name;
        this.file = file;
    }
	//get set
}

class FileV1{
    private Integer id;
    private String name;
    private PreviewV1 preview;
    private String url;
    public FileV1(Integer id, String name, PreviewV1 preview, String url) {
        this.id = id;
        this.name = name;
        this.preview = preview;
        this.url = url;
    }
	//get set
}

class PreviewV1{
    private Integer id;
    private String name;
    private String url;
    public PreviewV1(Integer id, String name, String url) {
        this.id = id;
        this.name = name;
        this.url = url;
    }
	//get set
}

Export

----------- conventional NPE Analyzing -----------
http://127.0.0.1/preview/miss.jpg

2. Optional process NPE

private static String defaultPreUrl="http://127.0.0.1/preview/miss.jpg";
private static FileV2 file2=new FileV2(1,"测试文件",null,"http://127.0.0.1/file/test.pdf");
private static ResourceV2 resource2 = new ResourceV2(1,"测试资源",file2);
@Test
public void NPEV2(){
   System.out.println("-----------Optional NPE判断-----------");
   String result = Optional.ofNullable(resource2)
           .flatMap(ResourceV2::getFile)
           .flatMap(FileV2::getPreview)
           .map(PreviewV2::getUrl)
           .orElse(Optional.of(defaultPreUrl)).get();
   System.out.println(result);
}
class ResourceV2{
    private Integer id;
    private String name;
    private FileV2 file;
    public ResourceV2(Integer id, String name, FileV2 file) {
        this.id = id;
        this.name = name;
        this.file = file;
    }
    public Optional<FileV2> getFile() {
        return Optional.ofNullable(file);
    }
    public void setFile(FileV2 file) {
        this.file = file;
    }
    //get set
}

class FileV2{
    private Integer id;
    private String name;
    private PreviewV2 preview;
    private String url;
    public FileV2(Integer id, String name, PreviewV2 previewV2, String url) {
        this.id = id;
        this.name = name;
        this.preview = preview;
        this.url = url;
    }
    public Optional<PreviewV2> getPreview() {
        return Optional.ofNullable(preview);
    }
    public void setPreview(PreviewV2 preview) {
        this.preview = preview;
    }
	//get set
}

class PreviewV2{
    private Integer id;
    private String name;
    private String url;
    public PreviewV2(Integer id, String name, String url) {
        this.id = id;
        this.name = name;
        this.url = url;
    }
    public Optional<String> getUrl() {
        return Optional.ofNullable(url);
    }
    public void setUrl(String url) {
        this.url = url;
    }
    //get set
}

Export

----------- Optional NPE Analyzing -----------
http://127.0.0.1/preview/miss.jpg

Published 43 original articles · won praise 28 · views 50000 +

Guess you like

Origin blog.csdn.net/u014395955/article/details/104040512