Table of Contents
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.
三. 注意事项
Home Java javaTutorial Optional class, a new feature of Java 8

Optional class, a new feature of Java 8

Feb 23, 2017 am 10:30 AM
java8 optional class new features

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
Copy after login
Copy after login

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
Copy after login

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
Copy after login
Copy after login
keyword, but provides a more elegant implementation of null determination to avoid NullPointException.

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()
Copy after login

Method:


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.


2. Basic usage

1. Object creation

Create an empty object
OptionalThe above example code calls the

empty()
Copy after login

method to create an empty

Optional<String>
Copy after login

object type.



Create object: empty is not allowed
Optional provides a method

of()
Copy after login

for creating a non-null object, which requires the parameters passed in It cannot be empty, otherwise

NullPointException
Copy after login

will be thrown. The example is as follows:


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()
Copy after login

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
Copy after login

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 Optional phone;
    private Optional<String> email;
    public User(String name, int age) {
        this.name = name;
        this.age = age;
    }
    // 省略setter和getter
}
Copy after login

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()
Copy after login

. 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
Copy after login

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));
Copy after login

3. Default behavior


The default behavior is when Optional does not meet the conditions The operation to perform, such as the

we used in the above example
orElse()
Copy after login

就是一个默认操作,用于在Optional对象为空时执行特定操作,当然也有一些默认操作是当满足条件的对象存在时执行的操作。

get()

get用于获取变量的值,但是当变量不存在时则会抛出

NoSuchElementException
Copy after login

,所以如果不确定变量是否存在,则不建议使用

orElse(T other)

当Optional的变量不满足给定条件时,则执行orElse,比如前面当str为null时,返回0。

orElseGet(Supplier<? extends X> expectionSupplier)
Copy after login

如果条件不成立时,需要执行相对复杂的逻辑,而不是简单的返回操作,则可以使用orElseGet实现:

long phone = optUser.map(User::getPhone).map(Optional::get).orElseGet(() -> {
    // do something here
    return -1L;
});
orElseThrow(Supplier<? extends X> expectionSupplier)
Copy after login

与get()方法类似,都是在不满足条件时返回异常,不过这里我们可以指定返回的异常类型。

ifPresent(Consumer)

当满足条件时执行传入的参数化操作。

三. 注意事项

Optional是一个final类,未实现任何接口,所以当我们在利用该类包装定义类的属性的时候,如果我们定义的类有序列化的需求,那么因为Optional没有实现Serializable接口,这个时候执行序列化操作就会有问题:

public class User implements Serializable{
    /** 用户编号 */
    private long id;
    private String name;
    private int age;
    private Optional phone;  // 不能序列化
    private Optional<String> email;  // 不能序列化
Copy after login

不过我们可以采用如下替换策略:

private long phone;
public Optional<Long> getPhone() {
    return Optional.ofNullable(this.phone);
}
Copy after login

看来Optional在设计的时候就没有考虑将它作为类的字段使用~

 以上就是Java8 新特性之 Optional 类 的内容,更多相关内容请关注PHP中文网(www.php.cn)!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Clair Obscur: Expedition 33 - How To Get Perfect Chroma Catalysts
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1677
14
PHP Tutorial
1278
29
C# Tutorial
1257
24
How to calculate date one year ago or one year later in Java 8? How to calculate date one year ago or one year later in Java 8? Apr 26, 2023 am 09:22 AM

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 Java 8: How to handle possibly null values ​​using orElseThrow() method Optional class in Java 8: How to handle possibly null values ​​using orElseThrow() method Jul 30, 2023 pm 01:57 PM

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

PHP 8.3 released: new features at a glance PHP 8.3 released: new features at a glance Nov 27, 2023 pm 12:52 PM

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

A guide to learn the new features of PHP8 and gain an in-depth understanding of the latest technology A guide to learn the new features of PHP8 and gain an in-depth understanding of the latest technology Dec 23, 2023 pm 01:16 PM

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 date one week later using Java 8? How to calculate date one week later using Java 8? Apr 21, 2023 pm 11:01 PM

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 Java 8: How to use flatMap() method to handle multiple levels of nested possibly null values Optional class in Java 8: How to use flatMap() method to handle multiple levels of nested possibly null values Jul 31, 2023 pm 10:33 PM

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

What are the new features of php8 What are the new features of php8 Sep 25, 2023 pm 01:34 PM

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: making programming more efficient Interpretation of new features of Go language: making programming more efficient Mar 10, 2024 pm 12:27 PM

[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

See all articles