Optional class, a new feature of Java 8
Summary: Optional is not a replacement for the null keyword, but provides a more elegant implementation of null judgment
NullPointException can be said to be an exception that all java programmers have encountered. , although Java has tried to free programmers from the suffering of pointers from the beginning of its design, pointers do actually exist, and Java designers can only make pointers simpler and easier to use in the Java language, but cannot completely Remove it, so we have the keyword
null
that we see every day.
Null pointer exception is a runtime exception. For this type of exception, if there is no clear handling strategy, then the best practice is to let the program hang up early. However, in many scenarios, developers do not have specific Handling strategy, but not aware of the existence of null pointer exception at all. When an exception does occur, the processing strategy is also very simple. Just add an if statement judgment where the exception exists. However, such a response strategy will cause more and more null judgments to appear in our program. We know a good Program design should minimize the occurrence of the null keyword in the code, and the
Optional
class provided by java8 not only reduces NullPointException, but also improves the beauty of the code. But first we need to make it clear that it is not a replacement for the
null
1. Intuitive experience Suppose we need to return the length of a string. If we do not use a third-party tool class, we need to call
str.length()
if(null == str) { // Null pointer determination
return 0;
}
return str.length();
If the Optional class is used, implement As follows:
return Optional.ofNullable(str).map(String::length).orElse(0);
Optional code is relatively concise. When the amount of code is large, we can easily forget it. Perform null determination, but using the Optional class will avoid such problems.
Create an empty object
Optionalempty()
Optional<String>
Create object: empty is not allowed
Optional provides a method
of()
NullPointException
Optional<String> optStr = Optional.of(str); // When str is null, NullPointException# will be thrown.
##Create object: allowed to be empty
If you are not sure whether there is a possibility of null value in the parameter passed in, you can use Optional's
ofNullable()
method to create an object , if the input parameter is null, an empty object is created. The example is as follows:
Optional<String> optStr = Optional.ofNullable(str); // If str is null, create an empty object
2. Streaming processing
Streaming processing is also a heavyweight new feature brought to us by java8, which makes our operation of collections more concise and efficient. The next article about the new features of java8 will provide a comprehensive introduction to churn processing. explain. Optional here also provides two basic churn processing: mapping and filtering.
For demonstration, we designed a
User
class, as follows:
/** * @author: zhenchao.Wang 2016-9-24 15:36:56 */ public class User { /** 用户编号 */ private long id; private String name; private int age; private Optionalphone; private Optional<String> email; public User(String name, int age) { this.name = name; this.age = age; } // 省略setter和getter }
Mobile phone and email are not necessary for a person, so we Use Optional definition.
Mapping: map and flatMap
Mapping is an operation that converts input into another form of output. For example, in the previous example, we input a string and output is the length of the string, which is a kind of implicit reflection, which we can achieve by using method
map()
. Suppose we want to get a person's name, then we can implement it as follows:
String name = Optional.ofNullable(user).map(User::getName).orElse("no name");
In this way, when the input parameter user is not empty, its name will be returned, otherwise
no name
If we want to get the phone or email through the above method, the above method will not work, because the map is returned after It is Optional. We call this Optional nesting. We must map once to get the result we want:
long phone = optUser.map(User::getPhone).map(Optional: :get).orElse(-1L);
In fact, at this time, a better way is to use flatMap to get the results we want in one step:
long phone = optUser.flatMap(User:: getPhone).orElse(-1L);
flapMap can flatten each stream returned by the method into one stream, which will be detailed in the next article dedicated to stream processing.
Filter: filter
filiter, as the name suggests, is a filtering operation. We can pass the filtering operation as a parameter to this method to achieve the purpose of filtering. Add what we want To screen adults over 18 years old, you can achieve the following:
optUser.filter(u -> u.getAge() >= 18).ifPresent(u -> System.out.println("Adult:" + u));
3. Default behavior
The default behavior is when Optional does not meet the conditions The operation to perform, such as the
orElse()
就是一个默认操作,用于在Optional对象为空时执行特定操作,当然也有一些默认操作是当满足条件的对象存在时执行的操作。
get()
get用于获取变量的值,但是当变量不存在时则会抛出
NoSuchElementException
,所以如果不确定变量是否存在,则不建议使用
orElse(T other)
当Optional的变量不满足给定条件时,则执行orElse,比如前面当str为null时,返回0。
orElseGet(Supplier<? extends X> expectionSupplier)
如果条件不成立时,需要执行相对复杂的逻辑,而不是简单的返回操作,则可以使用orElseGet实现:
long phone = optUser.map(User::getPhone).map(Optional::get).orElseGet(() -> { // do something here return -1L; }); orElseThrow(Supplier<? extends X> expectionSupplier)
与get()方法类似,都是在不满足条件时返回异常,不过这里我们可以指定返回的异常类型。
ifPresent(Consumer super T>)
当满足条件时执行传入的参数化操作。
三. 注意事项
Optional是一个final类,未实现任何接口,所以当我们在利用该类包装定义类的属性的时候,如果我们定义的类有序列化的需求,那么因为Optional没有实现Serializable接口,这个时候执行序列化操作就会有问题:
public class User implements Serializable{ /** 用户编号 */ private long id; private String name; private int age; private Optionalphone; // 不能序列化 private Optional<String> email; // 不能序列化
不过我们可以采用如下替换策略:
private long phone; public Optional<Long> getPhone() { return Optional.ofNullable(this.phone); }
看来Optional在设计的时候就没有考虑将它作为类的字段使用~
以上就是Java8 新特性之 Optional 类 的内容,更多相关内容请关注PHP中文网(www.php.cn)!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











Java8 calculates the date one year ago or one year later using the minus() method to calculate the date one year ago packagecom.shxt.demo02;importjava.time.LocalDate;importjava.time.temporal.ChronoUnit;publicclassDemo09{publicstaticvoidmain(String[]args ){LocalDatetoday=LocalDate.now();LocalDatepreviousYear=today.minus(1,ChronoUni

Optional class in Java8: How to use the orElseThrow() method to handle possibly null values Introduction: In Java development, we often encounter situations where we deal with possibly null values. In earlier versions of Java, we usually used null to indicate the absence of a value. However, there are some problems with using null. For example, we need to frequently determine whether it is null, and null pointer exceptions are prone to occur. To solve these problems, Java8 introduced

PHP8.3 released: Overview of new features As technology continues to develop and needs change, programming languages are constantly updated and improved. As a scripting language widely used in web development, PHP has been constantly improving to provide developers with more powerful and efficient tools. The recently released PHP 8.3 version brings many long-awaited new features and improvements. Let’s take a look at an overview of these new features. Initialization of non-null properties In past versions of PHP, if a class property was not explicitly assigned a value, its value

An in-depth analysis of the new features of PHP8 to help you master the latest technology. As time goes by, the PHP programming language has been constantly evolving and improving. The recently released PHP8 version provides developers with many exciting new features and improvements, bringing more convenience and efficiency to our development work. In this article, we will analyze the new features of PHP8 in depth and provide specific code examples to help you better master these latest technologies. JIT compiler PHP8 introduces JIT (Just-In-Time) compilation

How to calculate the date one week later in Java8 This example will calculate the date one week later. The LocalDate date does not contain time information. Its plus() method is used to add days, weeks, and months. The ChronoUnit class declares these time units. Since LocalDate is also an immutable type, you must use variables to assign values after returning. packagecom.shxt.demo02;importjava.time.LocalDate;importjava.time.temporal.ChronoUnit;publicclassDemo08{publicstaticvoidmain(String[

Optional class in Java8: How to use the flatMap() method to handle multi-level nested values that may be null Introduction: In software development, we often encounter situations where we deal with values that may be null. Previously, we might have used an if-else statement to check if an object was empty, but this approach was verbose and error-prone. Java 8 introduced the Optional class, which is a container object that can contain optional non-null values. Using the Optional class can be more concise and secure

New features of php8 include JIT compiler, type deduction, named parameters, union types, properties, error handling improvements, asynchronous programming support, new standard library functions and anonymous class extensions. Detailed introduction: 1. JIT compiler, PHP8 introduces the JIT compiler, which is an important performance improvement. The JIT compiler can compile and optimize some high-frequency execution codes in real time, thereby improving the running speed; 2. Type derivation , PHP8 introduces the type inference function, allowing developers to automatically deduce the type of variables when declaring variables, etc.

[Interpretation of new features of Go language: To make programming more efficient, specific code examples are needed] In recent years, Go language has attracted much attention in the field of software development, and its simple and efficient design concept has attracted more and more developers. As a statically typed programming language, Go language continues to introduce new features to improve development efficiency and simplify the code writing process. This article will provide an in-depth explanation of the latest features of the Go language and discuss how to experience the convenience brought by these new features through specific code examples. Modular development (GoModules) Go language from 1
