Share the example code of the newly introduced class Optional in Java8
Optional is a newly introduced class in Java8
This is a container that can be null object. If the value exists, the isPresent() method will return true, and calling the get() method will return the object.
java.lang.NullPointerException, as long as you dare to call yourself a Java programmer, you will be very familiar with this exception. In order to prevent this exception from being thrown, we often write code like this:
Person person = people.find("John Smith"); if (person != null) { person.doSomething(); }
Unfortunately, in most Java codes, we often forget to judge null references, so NullPointerException is It also followed.
"Null Sucks." This is Doug Lea's evaluation of null. As a Java programmer, if you still don’t know who Doug Lea is, then hurry up and make up the lessons. Without his contribution, we can only use Java’s most primitive equipment to handle multi-threading.
"I call it my billion-dollar mistake.", who is qualified to say this is the inventor of the null reference, Sir C. A. R. Hoare. You don't have to know Doug Lea, but you must know this old man, otherwise, you are not qualified to use quick sort.
In the Java world, a common way to solve the null reference problem is to use the Null Object mode. In this case, in the case of "nothing", Null Object is returned, and the client code does not need to judge whether it is empty. However, there are some problems with this approach. First, we definitely have to write code for Null Object, and if we want to apply this pattern at scale, we have to write Null Object for almost every class.
Fortunately, we have another option: Optional. Optional is an encapsulation of nullable objects, and it is not complicated to implement. In some languages, such as Scala, Optional implementation becomes part of the language. For Java programmers, Guava provides us with Optional support. Without further ado, let’s first talk about how to use Optional to complete the previous code.
Optional person = people.find("John Smith"); if (person.isPresent()) { person.get().doSomething(); }
If isPresent() returns false here, it means that this is an empty object. Otherwise, we can take out the content and do what we want to do.
If you are looking forward to a reduction in code size, I am afraid you will be disappointed here. In terms of code size alone, Optional even has more code than the original. But the good thing is that you will never forget to check for null, because what we get here is not an object of the Person class, but an Optional.
The following is the code for personal practice
public class OptionalTest { /** * of后面接给optional设置的值 但是不能为空 如果为空会报空指针异常 * @Title: ofTest * @Description: TODO * @param: * @return: void * @throws */ // @Test public void ofTest() { Optional<String> optional = Optional.of("123"); System.out.println(optional.get()); try { optional = Optional.of(null); System.out.println(optional.get()); //get方法是获取optional的值 类型取决于声明的时候 }catch(NullPointerException e) { System.out.println("空指针异常"); } } /** * ofNullable 和of类似 但是ofNullable可以设置null值 如果是Null值得话取值会报NoSuchElementException 异常 * @Title: ofNullableTest * @Description: TODO * @param: * @return: void * @throws */ // @Test public void ofNullableTest() { Optional<String> optional = Optional.ofNullable("123"); System.out.println(optional.get()); try { optional = Optional.ofNullable(null); System.out.println(optional.get()); }catch(NoSuchElementException e) { System.out.println("NoSuchElementException 异常"); } } /** * ifPresent用来判断optional中有没有值存在 如果有则为真 * @Title: isPresentTest * @Description: TODO * @param: * @return: void * @throws */ // @Test public void isPresentTest() { Optional<String> optional = Optional.ofNullable(null); if(optional.isPresent()) { System.out.println(optional.get()); } else { System.out.println("值为空"); } } /** * ifPresent和isPresent类似 只不过它支持λ表达式 * @Title: ifPresentTest * @Description: TODO * @param: * @return: void * @throws */ // @Test public void ifPresentTest() { Optional<String> optional = Optional.ofNullable("123"); optional.ifPresent(var ->{ System.out.println(var); }); } /** * orElse方法,如果值为空的话会用参数中的值去替换 即设置默认值 * @Title: orElseTest * @Description: TODO * @param: * @return: void * @throws */ // @Test public void orElseTest() { Optional<String> optional = Optional.ofNullable("123"); System.out.println(optional.orElse("有没有")); optional = Optional.ofNullable(null); System.out.println(optional.orElse("有没有")); } /** * orElseGet方法 和orElse类似 不过此方法接受Supplier接口的实现用来生成默认值 * @Title: orElseGetTest * @Description: TODO * @param: * @return: void * @throws */ // @Test public void orElseGetTest() { Optional<String> optional = Optional.ofNullable("123"); System.out.println(optional.orElseGet(()->"123456")); optional = Optional.ofNullable(null); System.out.println(optional.orElseGet(()->"123456")); } /** * map方法 如果有值则会对值进行mapping中的处理 处理结果存在则创建并返回Optional类型的结果 否则返回空 * @Title: mapTest * @Description: TODO * @param: * @return: void * @throws */ // @Test public void mapTest() { Optional<String> optional = Optional.ofNullable("abc"); System.out.println(optional.map(var->var.toUpperCase()).get()); } /** * flatMap和map类似 只不过mapping中必须返回Option类型的数据 * @Title: flatMapTest * @Description: TODO * @param: * @return: void * @throws */ // @Test public void flatMapTest() { Optional<String> optional = Optional.ofNullable("abc"); System.out.println(optional.flatMap(var->Optional.of(var.toUpperCase())).get()); } /** * filter对optional进行过滤,mapping中为过滤的条件 如果不满足条件 返回一个为空的Optional * @Title: filterTest * @Description: TODO * @param: * @return: void * @throws */ @Test public void filterTest() { try { Optional<String> optional = Optional.ofNullable("一二三四五六七八"); System.out.println(optional.filter(var ->var.length()>6).get()); System.out.println(optional.filter(var ->var.length()<6).get()); }catch(NoSuchElementException e) { System.out.println("optional的值为空"); } }
[Related recommendations]
1. Usage examples of Java 8’s new API--Optional
2. Parsing Java 8 Optional Class Instance Tutorial
The above is the detailed content of Share the example code of the newly introduced class Optional in Java8. For more information, please follow other related articles on the PHP Chinese website!

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

AI Hentai Generator
Generate AI Hentai for free.

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

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[

Preface Optional in Java is a container object, which can contain a non-null value or be empty. Its main purpose is to avoid null pointer exceptions when writing code. The complete usage of Optional in java8 is as follows: 1. Create an Optional object. You can create an Optional object containing a non-null value through the of() method, for example: Optionaloptional=Optional.of("value"); It can also be created through the ofNullable() method. An Optional object containing a possibly null value, for example: Optionaloptional=Optiona

How to use the Optional function to handle null values in Java In Java programming, we often encounter situations where null values are handled. Null pointer exception is a common error. In order to avoid this situation, Java8 introduced the Optional class to handle null value situations. The Optional class is a container class that can contain a non-empty value or no value. Using the Optional class, we can handle null value situations more gracefully and avoid null pointer exceptions. under

Java8's Clock class Java8 adds a Clock class for obtaining the current timestamp, or date and time information in the current time zone. Where System.currentTimeInMillis() and TimeZone.getDefault() were used before, they can be replaced by Clock. packagecom.shxt.demo02;importjava.time.Clock;publicclassDemo10{publicstaticvoidmain(String[]args){//Returnsthecurrenttimebase

Get the current timestamp in Java8. The Instant class has a static factory method now() that returns the current timestamp, as shown below: packagecom.shxt.demo02;importjava.time.Instant;publicclassDemo16{publicstaticvoidmain(String[]args) {Instanttimestamp=Instant.now();System.out.println("Whatisvalueofthisinstant"+timestamp.t

How to use predefined formatting tools to parse or format dates in Java8 packagecom.shxt.demo02;importjava.time.LocalDate;importjava.time.format.DateTimeFormatter;publicclassDemo17{publicstaticvoidmain(String[]args){StringdayAfterTommorrow="20180205 ";LocalDateformatted=LocalDate.parse

Determine whether two dates are equal in Java8 packagecom.shxt.demo02;importjava.time.LocalDate;publicclassDemo04{publicstaticvoidmain(String[]args){LocalDatedate1=LocalDate.now();LocalDatedate2=LocalDate.of(2018,2,5) ;if(date1.equals(date2)){System.out.println("Times are equal");}e
