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!

Java'splatformindependencemeansdeveloperscanwritecodeonceandrunitonanydevicewithoutrecompiling.ThisisachievedthroughtheJavaVirtualMachine(JVM),whichtranslatesbytecodeintomachine-specificinstructions,allowinguniversalcompatibilityacrossplatforms.Howev

To set up the JVM, you need to follow the following steps: 1) Download and install the JDK, 2) Set environment variables, 3) Verify the installation, 4) Set the IDE, 5) Test the runner program. Setting up a JVM is not just about making it work, it also involves optimizing memory allocation, garbage collection, performance tuning, and error handling to ensure optimal operation.

ToensureJavaplatformindependence,followthesesteps:1)CompileandrunyourapplicationonmultipleplatformsusingdifferentOSandJVMversions.2)UtilizeCI/CDpipelineslikeJenkinsorGitHubActionsforautomatedcross-platformtesting.3)Usecross-platformtestingframeworkss

Javastandsoutinmoderndevelopmentduetoitsrobustfeatureslikelambdaexpressions,streams,andenhancedconcurrencysupport.1)Lambdaexpressionssimplifyfunctionalprogramming,makingcodemoreconciseandreadable.2)Streamsenableefficientdataprocessingwithoperationsli

The core features of Java include platform independence, object-oriented design and a rich standard library. 1) Object-oriented design makes the code more flexible and maintainable through polymorphic features. 2) The garbage collection mechanism liberates the memory management burden of developers, but it needs to be optimized to avoid performance problems. 3) The standard library provides powerful tools from collections to networks, but data structures should be selected carefully to keep the code concise.

Yes,Javacanruneverywhereduetoits"WriteOnce,RunAnywhere"philosophy.1)Javacodeiscompiledintoplatform-independentbytecode.2)TheJavaVirtualMachine(JVM)interpretsorcompilesthisbytecodeintomachine-specificinstructionsatruntime,allowingthesameJava

JDKincludestoolsfordevelopingandcompilingJavacode,whileJVMrunsthecompiledbytecode.1)JDKcontainsJRE,compiler,andutilities.2)JVMmanagesbytecodeexecutionandsupports"writeonce,runanywhere."3)UseJDKfordevelopmentandJREforrunningapplications.

Key features of Java include: 1) object-oriented design, 2) platform independence, 3) garbage collection mechanism, 4) rich libraries and frameworks, 5) concurrency support, 6) exception handling, 7) continuous evolution. These features of Java make it a powerful tool for developing efficient and maintainable software.


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

SublimeText3 Linux new version
SublimeText3 Linux latest version

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

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

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.
