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 in Java

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article mainly introduces how to use Optional in Java. It is very detailed and has a certain reference value. Friends who are interested must finish it!

An interesting feature introduced from Java8 is the Optional class. The main problem solved by the Optional class is the infamous null pointer exception (NullPointerException) that every Java programmer knows very well.

In essence, this is a wrapper class with optional values, which means that the Optional class can either contain objects or be empty.

Optional is a powerful step for Java to implement functional programming and helps implement it in paradigms. But Optional clearly means more than that.

Let's start with a simple use case. Prior to Java 8, any call to access object methods or properties could result in NullPointerException:

String isocode = user.getAddress (). GetCountry (). GetIsocode (). ToUpperCase ()

In this small example, if we need to make sure that exceptions are not triggered, we have to explicitly check each value before accessing it:

If (user! = null) {Address address = user.getAddress (); if (address! = null) {Country country = address.getCountry (); if (country! = null) {String isocode = country.getIsocode (); if (isocode! = null) {isocode = isocode.toUpperCase ();}

As you can see, it can easily become lengthy and difficult to maintain.

To simplify this process, let's take a look at how it is done with the Optional class. From creating and validating an instance to using its different methods and combining it with other methods that return the same type, here is the moment to witness the miracle of Optional.

Create an Optional instance

Again, this type of object may contain a value or be empty. You can create an empty Optional using the method of the same name.

Test (expected = NoSuchElementException.class) public void whenCreateEmptyOptional_thenNull () {Optional emptyOpt = Optional.empty (); emptyOpt.get ();}

Not surprisingly, trying to access the value of the emptyOpt variable results in NoSuchElementException.

You can use the of () and ofNullable () methods to create an Optional that contains values. The difference between the two methods is that if you pass the null value as an argument, the of () method throws a NullPointerException:

@ Test (expected = NullPointerException.class) public void whenCreateOfEmptyOptional_thenNullPointerException () {Optional opt = Optional.of (user);}

You see, we haven't completely got rid of NullPointerException. Therefore, you should make it clear that you use of () when the object is not null.

If the object may be either null or non-null, you should use the ofNullable () method:

Optional opt = Optional.ofNullable (user)

Access the value of the Optional object

One of the ways to retrieve the actual value object from the Optional instance is to use the get () method:

@ Test public void whenCreateOfNullableOptional_thenOk () {String name = "John"; Optional opt = Optional.ofNullable (name); assertEquals ("John", opt.get ());}

However, as you can see, this method throws an exception when the value is null. To avoid exceptions, you can choose to verify whether there is a value first:

@ Test public void whenCheckIfPresent_thenOk () {User user = new User ("john@gmail.com", "1234"); Optional opt = Optional.ofNullable (user); assertTrue (opt.isPresent ()); assertEquals (user.getEmail (), opt.get (). GetEmail ());}

Another option to check whether there is a value is the ifPresent () method. In addition to performing the check, the method accepts a Consumer (consumer) parameter, which executes the incoming Lambda expression if the object is not empty:

Opt.ifPresent (u-> assertEquals (user.getEmail (), u.getEmail ()

In this example, the assertion is executed only if the user user is not null.

Next, let's look at ways to provide null values.

Returns the default value

The Optional class provides API to return the value of the object, or to return the default value when the object is empty.

The * method you can use here is orElse (), which works very directly. If there is a value, return the value, otherwise return the parameter value passed to it:

@ Test public void whenEmptyValue_thenReturnDefault () {User user = null; User user2 = new User ("anna@gmail.com", "1234"); User result = Optional.ofNullable (user) .orElse (user2); assertEquals (user2.getEmail (), result.getEmail ());}

Here the user object is empty, so user2 is returned as the default.

If the initial value of the object is not null, the default value is ignored:

@ Test public void whenValueNotNull_thenIgnoreDefault () {User user = new User ("john@gmail.com", "1234"); User user2 = new User ("anna@gmail.com", "1234"); User result = Optional.ofNullable (user) .orElse (user2); assertEquals ("john@gmail.com", result.getEmail ());}

The second API of the same type is orElseGet ()-- its behavior is slightly different. This method returns a value when it has a value, and if there is no value, it executes the Supplier functional interface passed as a parameter and returns its execution result:

User result = Optional.ofNullable (user) .orElseGet (()-> user2)

The difference between orElse () and orElseGet ()

At first glance, the two methods seem to have the same effect. However, this is not the case. Let's create some examples to highlight the similarities and differences between the two behaviors.

Let's first take a look at their behavior when the object is empty:

@ Test public void givenEmptyValue_whenCompare_thenOk () {User user = null logger.debug ("Using orElse"); User result = Optional.ofNullable (user) .orElse (createNewUser ()); logger.debug ("Using orElseGet"); User result2 = Optional.ofNullable (user). OrElseGet (()-> createNewUser ());} private User createNewUser () {logger.debug ("Creating NewUser"); return new User ("extra@gmail.com", "1234");}

In the above code, both methods call the createNewUser () method, which logs a message and returns a User object.

The code output is as follows:

Using orElse Creating New User Using orElseGet Creating New User

Thus, when the object is empty and returns the default object, there is no difference in behavior.

Let's look at a similar example next, but here Optional is not empty:

@ Test public void givenPresentValue_whenCompare_thenOk () {User user = new User ("john@gmail.com", "1234"); logger.info ("Using orElse"); User result = Optional.ofNullable (user) .orElse (createNewUser ()); logger.info ("Using orElseGet"); User result2 = Optional.ofNullable (user). OrElseGet (()-> createNewUser ());}

The output this time:

Using orElse Creating New User Using orElseGet

In this example, both Optional objects contain non-null values, and both methods return corresponding non-null values. However, the orElse () method still creates the User object. In contrast, the orElseGet () method does not create a User object.

When performing more intensive calls, such as invoking Web services or data queries, this difference can have a significant impact on performance.

Return exception

In addition to the orElse () and orElseGet () methods, Optional also defines orElseThrow () API, which throws an exception when the object is empty, rather than returning an alternative value:

@ Test (expected = IllegalArgumentException.class) public void whenThrowException_thenOk () {User result = Optional.ofNullable (user) .orElseThrow (()-> new IllegalArgumentException ());}

Here, if the user value is null, IllegalArgumentException is thrown.

This approach gives us a richer semantics to decide what exceptions to throw instead of always throwing a NullPointerException.

Now that we have a good understanding of how to use Optional, let's look at other ways to convert and filter Optional values.

Conversion value

There are many ways to convert the value of Optional. Let's start with the map () and flatMap () methods.

Let's start with an example of using map () API:

@ Test public void whenMap_thenOk () {User user = new User ("anna@gmail.com", "1234"); String email = Optional.ofNullable (user) .map (u-> u.getEmail ()) .orElse ("default@gmail.com"); assertEquals (email, user.getEmail ());}

Map () applies (calls) a function as an argument to the value, and then wraps the returned value in Optional. This makes it possible to make a chain trial call to the return value-- the next link here is orElse ().

Compared to this, flatMap () also needs a function as an argument, calls this function for the value, and then returns the result directly.

In the following operation, we added a method to the User class to return Optional:

Public class User {private String position; public Optional getPosition () {return Optional.ofNullable (position);} / /.}

Now that the getter method returns the Optional of the String value, you can use it as a parameter when calling flatMap () on the Optional object of User. The value returned is the unwrapped String value:

@ Test public void whenFlatMap_thenOk () {User user = new User ("anna@gmail.com", "1234"); user.setPosition ("Developer"); String position = Optional.ofNullable (user) .flatMap (u-> u.getPosition ()) .orElse ("default"); assertEquals (position, user.getPosition (). Get ());}

Filter value

In addition to converting values, the Optional class also provides a way to "filter" values by condition.

Filter () takes a Predicate parameter and returns a value whose test result is true. If the test result is false, an empty Optional is returned.

Let's look at an example of accepting or rejecting User based on basic email authentication:

@ Test public void whenFilter_thenOk () {User user = new User ("anna@gmail.com", "1234"); Optional result = Optional.ofNullable (user) .filter (u-> u.getEmail ()! = null & & u.getEmail (). Contains ("@")); assertTrue (result.isPresent ());}

If you pass the filter test, the result object contains a non-null value.

The above is all the content of the article "how to use Optional in Java". Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!

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

Development

Wechat

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

12
Report