JDK8,Optional

   As a programmer, you certainly come across NullPointerException, the exception for fledgling newcomer or seasoned veteran rivers and lakes are inevitable pain, and yet is so powerless, in order to solve it, you can only use a certain value before its empty sentenced to treatment. However, this would make the code bloat. Fortunately jdk8 optional introduced to deal with the problem of null, null no longer allows us to do too much concern.

    Written before the first show of jdk8

1 // First before jdk8
2 Long id = 0L;
3 User user = getUserById(id);
4 if (user != null) {
5     String name = user.getName();
6     System.out.println("name=" + name);
7 }

If the user does not get a method for determining empty, the following properties can easily get its null pointer exception.

jdk 8 wording

1 User userById = Optional.ofNullable(getUserById(id)).orElse(new User());
2 String name = userById.getName();
3 System.out.println("new name=" + name);

Such an approach would avoid the empty judgment, the code is very simple

The method described below under the optional

1, first configuration of, ofNullable, empty

. 1  // empty empty optional objects Construction 
2 Optional The <Object> = empty Optional.empty ();
 . 3  
. 4  // of the user configuration optional objects, user objects is not empty, if the time is empty, packets will build nullPointerException 
. 5 the User user = new new the User ();
 . 6 optional the <the User> userOptional = Optional.of (user);
 . 7  
. 8  // ofNull configuration optional objects, the internal user if it is empty, empty optional objects to build 
. 9 optional the <the User> userOptionalOfNull = Optional.ofNullable (User);
 10  
. 11 Optional The <Object> = objectOptional Optional.of ( null );
 12 is  System.out.println (objectOptional);
 13 is 
14 
15 Exception in thread "main" java.lang.NullPointerException
16     at java.util.Objects.requireNonNull(Objects.java:203)
17     at java.util.Optional.<init>(Optional.java:96)
18     at java.util.Optional.of(Optional.java:108)
19     at com.zbb.jdk.jdk8Test.optional.OptionalOfTest.main(OptionalOfTest.java:32)

Look ofNullable source method

2, get ifPresent, get, isPresent

. 1 Optional The <the User> userOptional = Optional.ofNullable (getUserById (ID));
 2  // isPresent optional determines whether the object exists, if present, returns true, otherwise to false 
. 3  IF (userOptional.isPresent ()) {
 . 4      // has to determine the presence of
 5      // GET Optional created if there exists a value, this value is returned, otherwise throw NoSuchElementException 
6      the User the User = userOptional.get ();
 7      System.out.println ( "name" + user.getName () );
 8  }
 . 9  
10  // value exists Optional created, then performing the method call, or do nothing
 11  // parameters ifPresent method is a function interface, the method returns no value can be directly used lambda expressions 
12 userOptional.ifPresent(user -> System.out.println("name=" + user.getName()));

Examples of the beginning of such a change can also be used isPresent, but this original sentence and empty and there is no difference, but the method is different, in essence, no difference, it is not recommended. Look at the source code of these methods

3, get orElse, orElseGet, orElseThrow

. 1 Optional The <the User> userOptional = Optional.ofNullable (getUserById (ID));
 2  
. 3  // orElse value is returned if there are optional value, if not it returns a default value
 4  // Default is we create a class 
. 5 the User = userOptional.orElse User ( new new the User ( "Xiaohong", "123456789" ));
 . 6 System.out.println ( "name =" + user.getName ()); // name = Xiaohong
 . 7  
. 8  // orElseGet If optional has a value return value, if not, performing a Supplier interface returns the resulting value 
. 9 the User userOrElseGet userOptional.orElseGet = (() -> new new the User ( "xiaohongGet", "123456789" ));
 10System.out.println ( "name =" + userOrElseGet.getName ()); // name = xiaohongGet
 . 11  
12 is  // orElseThrow value is returned if there are optional value, if not, return to a specified exception generated Supplier interfaces 
13 userElseThrow = userOptional.orElseThrow the User (() -> new new exception ( "userOptional is empty!" ));
 14  
15  // is empty, the thrown exception 
16 exception in the Thread "main" java.lang.Exception: userOptional is air!
. 17      AT main com.zbb.jdk.jdk8Test.optional.OptionalOrElse.lambda $ $. 1 (OptionalOrElse.java:29 )
 18 is      AT java.util.Optional.orElseThrow (Optional.java:290 )
 . 19     at com.zbb.jdk.jdk8Test.optional.OptionalOrElse.main(OptionalOrElse.java:29)

Look at the source code

Similarly orElseThrow

4, filtration filter

. 1 Optional The <the User> userOptional = Optional.ofNullable ( new new the User ( "Xiao", "123456" ));
 2  
. 3  // value of the optional qualified, the optional object is returned, otherwise empty optional objects 
. 4 the User User userOptional.filter = (U -> NAME.equals (u.getName ())) orElse (. new new the User ( "not satisfied", "" ));
 . 5 System.out.println ( "name =" + user.getName ()); // name = Xiao

5, the conversion map, flatMap

1 Optional<String> optional = Optional.ofNullable("zhang,san");
2 
3 //map  optional对象存在就执行Funciton函数
4 // 可以返回任意类型的值
5 // 该函数式接口对optional对象中的值进行修改,返回修改后的值
6 Optional<String[]> optionalMap = optional.map(s -> s.split(",")); //Optional[[Ljava.lang.String;@19dfb72a]
7 
8 // flatMap方法中的lambda表达式返回值必须是Optionl实例
9 Optional<String> optionalFlatMap = optional.flatMap(s -> Optional.of("lisi"));//Optional[lisi]

看源码知道,map 和 flatmap 都是如果optional中的值存在,就对该值执行提供的Function函数调用,返回一个optional类型的值,否 
则就返回一个空的optional对象。

    The biggest difference is after the map function to perform any type of data, and then call the end of the map will be optional on the results of the package, and is a flatmap is optional instance After you have performed, the results will not flatmap optional package.

Guess you like

Origin www.cnblogs.com/zhoubb/p/11610754.html