JAVA 8 Optional class introduction and its source code, javaoptional
What is an Optional object?
The so-called Optional object in Java 8 is a container object, which can contain a null or non-null value. If the value is not null, true is returned when the isPresent () method is called, and the get () method is called.
In addition, this object has other methods:
For example, you can use the orElse () method to set the default value for the Optional object (when the value is null, the default value is used );
Use the ifPresent () method to execute a code segment (when the value is not null ).
Optional is mainly used in Stream of Java 8. For example:
Package optional; import java. util. optional; import java. util. stream. stream; public class Snippet {public static void main (String [] args) {Stream <String> names = Stream. of ("Lamurudu", "Okanbi", "Oduduwa"); Optional <String> startswl = names. filter (name-> name. startsWith ("L ")). findFirst (); // determines whether it is not null if (startswl. isPresent () {System. out. println (startswl. get ();} // if is null: Print "null"; if is not null: print the original value System. out. println (startswl. orElse ("null"); // if the value is not null, execute the Lambda expression startswl. ifPresent (name-> {String s = name. toUpperCase (); System. out. println (s );});}}
Benefits of using Optional objects
Reduce NullPointerException exceptions
Write more elegant code
Source code and Examples
The Optional class attributes and methods are as follows:
Let's take a look at the two member attributes first;
Member attributes
One is the EMPTY constant, that is, the Optional object that stores null values, and the other is the value, that is, the stored value, which can be null or non-null values;
/** * Common instance for {@code empty()}. */ private static final Optional<?> EMPTY = new Optional<>(); /** * If non-null, the value; if null, indicates no value is present */ private final T value;
Constructor
Both constructor methods are private.
1. Create an Optional object that contains null values;
2. Create a non-null Optional object;
private Optional() { this.value = null; }
private Optional(T value) { this.value = Objects.requireNonNull(value); }
Empty () method
This method is very simple. The function is to return an Optional instance, where the stored value is null. The source code is as follows:
public static<T> Optional<T> empty() { @SuppressWarnings("unchecked") Optional<T> t = (Optional<T>) EMPTY; return t; }
Of (T value) Method
Return an Optional object that contains non-null values.
public static <T> Optional<T> of(T value) { return new Optional<>(value); }
OfNullable (T value) Method
Return an Optional object that can contain null values.
public static <T> Optional<T> ofNullable(T value) { return value == null ? empty() : of(value); }
Get () method
Obtain the value in the Optional object. If the value is null, A NoSuchElementException exception is thrown.
public T get() { if (value == null) { throw new NoSuchElementException("No value present"); } return value; }
IsPresent () method
It's easy to judge whether the value is not null
public boolean isPresent() { return value != null; }
IfPresent (Consumer <? Super T> consumer) Method
If the value is not null, run the consumer command.
public void ifPresent(Consumer<? super T> consumer) { if (value != null) consumer.accept(value); }
For example, the ifPresent method executes the Lambda expression, converts the value to uppercase, and prints:
Package optional; import java. util. optional; public class Snippet {public static void main (String [] args) {Optional <String> test = Optional. ofNullable ("abcDef"); // if the value is not null, execute the Lambda expression, test. ifPresent (name-> {String s = name. toUpperCase (); System. out. println (s) ;}); // print ABCDEF }}
Filter (Predicate <? Super T> predicate) Method
You can see the method name. This method is a filtering method that filters out Optional objects that meet the conditions. The conditions here are defined using Lambda expressions,
If the input parameter predicate object is null, an NullPointerException exception is thrown,
If the value of the Optional object is null, the Optional object is directly returned,
If the value of the Optional object meets the conditions (defined by Lambda expressions), this value is returned. Otherwise, an empty Optional object is returned.
The source code is as follows:
public Optional<T> filter(Predicate<? super T> predicate) { Objects.requireNonNull(predicate); if (!isPresent()) return this; else return predicate.test(value) ? this : empty(); }
Example:
Package optional; import java. util. optional; public class Snippet {public static void main (String [] args) {Optional <String> test = Optional. ofNullable ("abcD"); // Optional object Optional whose filter value is less than 3 <String> less3 = test. filter (value)-> value. length () <3); // print the result System. out. println (less3.orElse ("does not meet the conditions, do not print the value! "));}}
Map (Function <? Super T ,? Extends U> mapper) Method
The previous filter method is mainly used for filtering. It generally does not modify the value in Optional. The map method is generally used to modify the value and return the modified Optional object.
If the mapper object of the input parameter is null, an NullPointerException exception is thrown,
If the value of the Optional object is null, the Optional object is directly returned,
Finally, execute the passed lambda expression and return the Optional object operated by the lambda expression.
public<U> Optional<U> map(Function<? super T, ? extends U> mapper) { Objects.requireNonNull(mapper); if (!isPresent()) return empty(); else { return Optional.ofNullable(mapper.apply(value)); } }
Example:
Package optional; import java. util. optional; public class Snippet {public static void main (String [] args) {Optional <String> test = Optional. ofNullable ("abcD"); // change the value to uppercase Optional <String> less3 = test. map (value)-> value. toUpperCase (); // print the result ABCD System. out. println (less3.orElse ("value is null, do not print! "));}}
FlatMap (Function <? Super T, Optional <U> mapper) Method
The flatMap method is basically the same as the map method. The only difference is that,
If you use the flatMap method, you need to convert the return value to an Optional object in the Lambda expression,
This step is not required to use the map method, because the Optional. ofNullable method has been called in the source code of the map method;
Source code:
public<U> Optional<U> flatMap(Function<? super T, Optional<U>> mapper) { Objects.requireNonNull(mapper); if (!isPresent()) return empty(); else { return Objects.requireNonNull(mapper.apply(value)); } }
Example:
Package optional; import java. util. optional; public class Snippet {public static void main (String [] args) {Optional <String> test = Optional. ofNullable ("abcD"); // use flatMap to change the value to uppercase Optional <String> less3 = test. flatMap (value)-> Optional. ofNullable (value. toUpperCase (); // use map to change the value to uppercase // Optional <String> less3 = test. map (value)-> value. toUpperCase (); // print the result ABCD System. out. println (less3.orElse (" The value is null and does not print! "));}}
OrElse (T other) Method
Very simple. If the value is null, the input value is returned; otherwise, the original value is returned;
Source code:
public T orElse(T other) { return value != null ? value : other; }
OrElseGet (Supplier <? Extends T> other) Method
The function is similar to orElse (T other). However, the optional values of this method are obtained not directly through parameters, but by calling the passed Lambda expression.
Source code:
public T orElseGet(Supplier<? extends T> other) { return value != null ? value : other.get(); }
Example:
Package optional; import java. util. optional; public class Snippet {public static void main (String [] args) {Optional <String> test = Optional. ofNullable (null); System. out. println (test. orElseGet ()-> "hello"); // print hello }}
OrElseThrow (Supplier <? Extends X> predictionsupplier) Method
When the value is null, a specified exception occurs based on the input Lambda expression.
Source code
public <X extends Throwable> T orElseThrow(Supplier<? extends X> exceptionSupplier) throws X { if (value != null) { return value; } else { throw exceptionSupplier.get(); } }
Example:
Package optional; import java. util. optional; public class Snippet {public static void main (String [] args) {Optional <String> test = Optional. ofNullable (null); // The Lambda expression here references System for the constructor. out. println (test. orElseThrow (NullPointerException: new); // print hello }}
References
Jdk1.8.0 _ 31 source code
Https://blog.idrsolutions.com/2015/04/java-8-optional-class-explained-in-5-minutes/
Https://www.voxxed.com/blog/2015/05/why-even-use-java-8-optional/
Http://unmi.cc/proper-ways-of-using-java8-optional/