JDK1.8 series articles

  • New in JDK1.8 (1) : Lambda expressions
  • New in JDK1.8 (2) : Optional
  • JDK1.8 new feature (3) : Stream
  • New in JDK1.8 (4) : Maps
  • New JDK1.8 feature (5) : new date and time API

Nullpointerexceptions are ubiquitous in our development. We often need defensive checks to avoid nullpointerexceptions, so we see them in our code. = null). Fortunately, in JDK1.8, Java provides us with an Optional class, which allows us to avoid the complicated non-empty judgment. Let’s take a quick look at the methods provided in Optional:

methods describe
of If the specified value is null, a NullPointerException is thrown
empty Create an empty Optional object
ofNullable If the specified value is null, an empty Optional object is created
get This value is returned if the Optional is created, otherwise NoSuchElementException is thrown
orElse Return this value if the Optional value exists, otherwise a default value is returned
orElseGet Return this value if it exists in the Optional created, or a value generated by the Supplier interface otherwise
orElseThrow Returns a value if it exists in the Optional created, or raises an exception generated by the specified Supplier interface
filter If the value of “Optional” meets the criteria in filter, an Optional object containing this value is returned. Otherwise, an empty Optional object is returned
map If the value in the Optional creation exists, the supplied Function call is made to that value
flagMap If the value in the created Optional exists, the provided Function call is made to that value, returning a value of type Optional, otherwise an empty Optional object is returned
isPresent Return true if the value in Optional is present, false otherwise
ifPresent If the value in Optional is created, then the call to this method is executed, otherwise nothing is done

The Optional class provides an Optional method. I’m not afraid of NullPointerException ** finding me in my code anymore.

Optional class

Let’s write a few examples to see what each method does:

One of them,

If the specified value is null, a NullPointerException is thrown

// Create a String ofOptional Optional<String> ofOptional = option.of (" span "); Optional<String> nullOptional = Optional. Of (null);Copy the code

Output:

java.lang.NullPointerException at java.util.Objects.requireNonNull(Objects.java:203) at Java. Util. Optional. < init > (96) Optional. Java: · · · · · ·Copy the code

Second, the ofNullable

If the specified value is null, an empty Optional object is created

// Create Optional<String> nullOptional1 = Optional. OfNullable (null); // Create Optional<String> nullOptional1 = Optional. Optional<String> nullOptional2 = Optional.ofNullable("list");Copy the code

Third, the empty

Create an empty Optional object

// Create an emptyOptional String object of type Optional<String> emptyOptional = option.empty ();Copy the code

Fourth, the get

If we create values were found to exist in the Optional object returns this value, if there is no value exists, will throw NoSuchElementException exception, as follows:

Optional<String> stringOptional = Optional.of("Zhang");
System.out.println(stringOptional.get());
Copy the code

Output:

Zhang SANCopy the code

A case where NoSuchElementException is thrown

Optional<String> emptyOptional = Optional.empty();
System.out.println(emptyOptional.get());
Copy the code

Output:

java.util.NoSuchElementException: No value present at java.util.optional. Get (Optional. Java :135) at com.***.test.test4 (test.java :93)Copy the code

Fifth, orElse

Return this value if the Optional value exists, otherwise a default value is returned

Optional<String> stringOptional = Optional. Of (" zhang 3 "); System.out.println(stringOptional.orElse("zhangsan")); Optional<String> emptyOptional = Optional.empty(); System. The out. Println (emptyOptional. OrElse (" li si "));Copy the code

Output:

Tom, dick and harryCopy the code

Six, orElseGet

Return this value if it exists in the Optional created, or a value generated by the Supplier interface otherwise

Optional<String> stringOptional = Optional. Of (" zhang 3 "); System.out.println(stringOptional.orElseGet(() -> "zhangsan")); Optional<String> emptyOptional = Optional.empty(); System.out.println(emptyOptional.orElseGet(() -> "orElseGet"));Copy the code

Output:

Zhang SAN orElseGetCopy the code

Seven, orElseThrow

Return the value of Optional if it exists, otherwise raise an exception generated by the specified Supplier interface first by defining an exception class

class CustomException extends RuntimeException { private static final long serialVersionUID = -4399699891687593264L; Public CustomException() {super(" CustomException "); } public CustomException(String message) { super(message); }}Copy the code

The test code is as follows

Optional<String> stringOptional = Optional. Of (" zhang 3 "); System.out.println(stringOptional.orElseThrow(CustomException::new)); Optional<String> emptyOptional = Optional.empty(); System.out.println(emptyOptional.orElseThrow(CustomException::new));Copy the code

Output:

com.***.Test$CustomException: Custom exception at com. * * *. The Test. The lambda $test4 $1 (JiankeTest. Java: 96) at Java. Util. Optional. The orElseThrow ats (Optional. Java: 290) Com. * * *. Test. Test4 (96) JiankeTest. Java: · · · · · ·Copy the code

Eight, the filter

If the value of “Optional” meets the criteria in filter, an Optional object containing this value is returned. Otherwise, an empty Optional object is returned

Optional<String> stringOptional = Optional.of("zhangsan"); System.out.println(stringOptional. Filter (e -> e.long () > 5).orelse ()); stringOptional = Optional.empty(); System.out.println(stringOptional.filter(e -> e.length() > 5).orElse("lisi"));Copy the code

The output

zhangsan
lisi
Copy the code

The filter method in Optional is different from the filter method in Stream. The filter method in Stream is different from the filter method in Optional. The filter method in Stream is different from the filter method in Optional. Think of an Optional as a Stream that contains at most one element.

Nine, the map

If the value in the Optional creation exists, the supplied Function call is made to that value

// The map method executes the lambda argument passed in and changes the value of the Optional instance. The returned value is still an Optional object Optional<String> stringOptional = Optional.of("zhangsan"); System.out.println(stringOptional. Map (e -> e.topperCase ()).orelse (" failed ")); stringOptional = Optional.empty(); System.out.println(stringOptional. Map (e -> e.topperCase ()).orelse (" failed "));Copy the code

Output:

ZHANGSAN failureCopy the code

Ten, flagMap

If the value in the created Optional is present, the provided Function call is made to that value, returning an Optional value, or an empty Optional object otherwise. The mapper function of the flatMap method must return Optional. The mapping function of the map method can return T of any type. At the end of the call, flatMap does not encapsulate the result with Optional.

// The return value of the lambda expression in the map method can be any type, and is wrapped as Optional before the map function returns. // But the lambda expression in the flatMap method must return an Optionl instance Optional<String> stringOptional = option. of("zhangsan"); System.out.println(stringOptional. FlatMap (e -> Optional. Of ("lisi")).orelse (" fail ")); stringOptional = Optional.empty(); System.out.println(stringoption.flatmap (e -> option.empty ()).orelse (" fail "));Copy the code

Output:

Lisi failureCopy the code

Eleven, isPresent

Return true if the value in Optional is present, false otherwise

Optional<String> stringOptional = Optional.of("zhangsan");
System.out.println(stringOptional.isPresent());

Optional<String> stringOptional2 = Optional.empty();
System.out.println(stringOptional2.isPresent());
Copy the code

Output:

true
false
Copy the code

Twelve, ifPresent

If the value in Optional is created, then the call to this method is executed, otherwise nothing is done

// The ifPresent method takes an implementation class of the Consumer. The Consumer class contains an abstract method that handles the value passed in but does not return a value. Optional<String> stringOptional = Optional.of("zhangsan"); StringOptional. IfPresent (e -> system.out.println) stringOptional. IfPresent (e -> System. + e));Copy the code

Output:

I was dealt with... zhangsanCopy the code

The public,

If you want to see my updated Java direction learning article in the first time, you can follow the public account ** [Lucas’s Coffee shop]. All learning articles public number first, please scan the code to pay attention to oh! Java8 new features learning videos please pay attention to the public number, private message [Java8] ** can be free unscripted access to learning videos.