Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use Optional of Java8

2025-01-15 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly explains "how to use Optional in Java8". The content in the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "how to use Optional in Java8".

Introduction

Students who have written Java programs have generally encountered NullPointerException-in order not to throw this exception, we will write the following code:

User user = getUserById (id); if (user! = null) {String username = user.getUsername (); System.out.println ("Username is:" + username); / / use username}

But most of the time, we may forget to write if (user! = null)-- it's fine if we find it in the development phase, but if there's no problem with the test during the development phase, we'll get NullPointerException when it comes online. The picture is so beautiful that I dare not think about it any more.

To solve this awkward situation, JDK finally added the Optional class to Java8. Optional's javadoc introduction:

A container object which may or may not contain a non-null value. If a value is present, isPresent () will return true and get () will return the value.

This is a container that can contain or not contain non-null values. If the value exists, the isPresent () method returns true, and a call to the get () method returns the object.

I. brief introduction

Optional class is an Optional class of the same name introduced by Java8 in order to solve the problem of null value judgment by referring to the Optional class of google guava class library. Using Optional class can avoid explicit null value judgment (defensive check of null) and avoid NPE (NullPointerException) caused by null.

Let's look at a piece of code:

Public static String getGender (Student student) {if (null = = student) {return "Unkown";} return student.getGender ();}

This is a method to get the gender of the student. The method input parameter is a Student object. In order to prevent the student object from being null, a defensive check is done: if the value is null, return "Unkown".

Take a look at the optimized method using Optional:

Public static String getGender (Student student) {return Optional.ofNullable (student) .map (u-> u.getGender ()) .orElse ("Unkown");}

As you can see, the Optional class combined with the use of lambda expressions can make the developed code more concise and elegant.

Second, the creation of Optional object

Let's take a look at some of the source code of the Optional class:

Private static final Optional EMPTY = new Optional (); private final T value; private Optional () {this.value = null;} private Optional (T value) {this.value = Objects.requireNonNull (value);} public static Optional empty () {@ SuppressWarnings ("unchecked") Optional t = (Optional) EMPTY; return t } public static Optional of (T value) {return new Optional (value);} public static Optional ofNullable (T value) {return value = = null? Empty (): of (value);}

As you can see, both constructors of the Optional class are private, so new Optional () cannot be displayed outside the class to create the Optional object, but the Optional class provides three static methods empty (), of (T value), and ofNullable (T value) to create the Optinal object, as shown in the following example:

/ / 1. Create an Optional object with empty wrapper object value Optional optStr = Optional.empty (); / 2, create Optional object with nonempty wrapper object value Optional optStr1 = Optional.of ("optional"); / / 3. Create Optional object with null wrapper object value Optional optStr2 = Optional.ofNullable (null)

Third, the use of typical interfaces of Optional class

Taking some typical scenarios as examples, the usage of common Optional API interfaces is listed and the corresponding code is attached.

As mentioned earlier in javadoc, the isPresent () method of Optional is used to determine whether it contains a value, and get () is used to get the value contained by Optional-- it is worth noting that if the value does not exist, that is, if the get () method is called on an Optional.empty, a NoSuchElementException exception will be thrown.

Assuming that getUserById is an objective and unchangeable method, we can now write the following code using both isPresent and get methods:

Optional user = Optional.ofNullable (getUserById (id)); if (user.isPresent ()) {String username = user.get () .getUsername (); System.out.println ("Username is:" + username); / / use username}

It seems that the code is a bit beautiful-but in fact this is not fundamentally different from the previous code that judged the null value, but instead uses Optional to encapsulate the value, increasing the amount of code. So let's take a look at what other ways Optional provides for us to use Optional better (in the right posture).

3.1 get () method

Take a brief look at the source code of the get () method:

Public T get () {if (value = = null) {throw new NoSuchElementException ("No value present");} return value;}

As you can see, the get () method is mainly used to return the actual value of the wrapper object, but if the wrapper object value is null, a NoSuchElementException exception is thrown.

3.2 isPresent () method

Source code for the isPresent () method:

Public boolean isPresent () {return value! = null;}

As you can see, the isPresent () method is used to determine whether the value of the wrapper object is not empty. Let's look at a bad piece of code:

Public static String getGender (Student student) {Optional stuOpt = Optional.ofNullable (student); if (stuOpt.isPresent ()) {return stuOpt.get () .getGender ();} return "Unkown";}

This code implements the logic in the first chapter (introduction), but this usage not only does not reduce the defensive check of null, but also increases the process of Optional packaging, which runs counter to the original intention of Optional design, so it is necessary to avoid this bad use in development.

3.3The ifPresent () method

Source code for the ifPresent () method:

Public void ifPresent (Consumer

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report