Option is a good thing that most people really don't know how to use!
AD |
OverviewNullPoInterException, ChInese name:Null poInter exceptionNPE, also known as NPE, is one of the most common error anomalies In software systems.Long ago, the Google Guava project IntroducedOptionalNull poInter exceptionNullTo expect programmers to write code that is both neat and more readable
Overview
NullPoInterException, ChInese name:Null poInter exceptionNPE, also known as NPE, is one of the most common error anomalies In software systems.
Long ago, the Google Guava project IntroducedOptionalNull poInter exceptionNullTo expect programmers to write code that is both neat and more readable.
OptionalNull
The followIng is a common parameter Null detection code, with an example as follows.
//DetermIne If the admInistrative region is emptyIfCountry!=Null{//DetermIne whether the admInistrative city is empty at the upper level of the admInistrative districtIfCountry. GetCity!=Null{//DetermIne whether the admInistrative provInce is empty at the upper level of the admInistrative cityIfCountry. GetCity. GetProvInce!=Null{//ObtaIn data related to the correspondIng admInistrative provInceReturnCountry. GetCity. GetProvInce. GetName}}}
This is still the most common three-layer judgment. If there is a large section of busIness logic processIng, you will fInd that the code not only looks bulky, but also dIfficult to read and has poor readability!
Optional source code diagram
If adjusted to useOptionalTo write it, it can be converted to the followIng notation:
//StrIngresult=Optional. of NullableCountry.MapCountry::GetCity.MapCity::GetProvInce.MapProvInce::GetName.OrElseError
adoptOptionalAfter programmIng, should the readability and cleanlIness of the entire code be much cleaner!
API Introduction
In JDK8, Option has a total of 12 core methods, let's take a look at their usage toGether!
2.1. empty
The empty method Returns an Optional Instance that does not contaIn a Value. It is meanIngless to use it alone and is maInly used In conjunction with other methods.
OptionalOptional=Optional. emptySystem. OutPrIntlnOptional--Optional. empty
2.2of
of Optional Null poInter exception.
//OptionalOptional=Optional.of"HelloWorld"System. OutPrIntlnOptional--Optional[HelloWorld]//Null poInter exceptionOptionalOptional=Optional.ofNullSystem. OutPrIntlnOptional--ExceptionInthread"maIn"java.lang.NullPoInterExceptionatjava.util.Objects.requireNonNullObjects. java:two hundred and threeatjava.util.Optional.<Init>Optional. java:nInety-sixatjava.util.Optional.ofOptional. java:one hundred and eight
2.3Of Nullable
The Of Nullable method will Return an Optional Instance, and If the passed In Value is not empty, it will Return an object contaInIng the specIfied Value; If Null is passed In, an empty object withOut any Values will be Returned, which is the first IntroducedOptional. emptyObject.
//OptionalOptional=Optional. of Nullable"HelloWorld"System. OutPrIntlnOptional--Optional[HelloWorld]//emptyOptionalOptional=Optional. of NullableNullSystem. OutPrIntlnOptional--Optional. empty
2.4isPresent
The isPresent method is used to determIne whether an Instance contaIns a Value. If it contaIns a non Null Value, it Returns True, otherwise it Returns False.
//Truebooleanrs1=Optional. of NullableHello.isPresentSystem.Out.PrIntlnrs1//Falsebooleanrs2=Optional. of NullableNull.isPresentSystem.Out.PrIntlnrs2--TrueFalse
2.5Get
The Get method Returns the current Value If the Instance contaIns non Null Values; Otherwise, a NoSushElementException exception will be thrown.
//Objectrs=Optional. of Nullable"HelloWorld".GetSystem.Out.PrIntlnrs--HelloWorld//NoSushElementExceptionObjectrs=Optional. of NullableNull.GetSystem.Out.PrIntlnrs--ExceptionInthread"maIn"java.util.NoSuchElementException:NoValuepresentatjava.util.Optional.GetOptional. java:one hundred and thirty-five
2.6IfPresent
IfPresent Consumer.
Optional. of Nullable"HelloWorld".IfPresentx->{System.Out.PrIntlnx}--HelloWorld
2.7filter
The filter method is used to filter Out values that do not meet the criteria and receive aPredicateParameter, If the condition is met, will Return the currentOptionalInstance, otherwise Return empty Instance.
Optional. of Nullable"HelloWorld". filterx->x.contaInsHello.IfPresentx->{System.Out.PrIntlnx}--HelloWorld
2.8Map
The Map method is the core method for chaIn callIng to avoid Null poInters. When an Instance contaIns a value, the passed In method is executed on the valueFunctionFunction Interface method and Returns a New value representIng the result valueOptionalInstance, which means repackagIng the Returned results asOptionalObject.
Optional. of Nullable"Hello+World".Mapt->{Ift.contaIns+{Returnt.replace+,""}Returnt;}.IfPresentt->{System.Out.PrIntlnt}--HelloWorld
2.9flatMap
The flatMap method is similar to the Map method, with the only dIfference beIng that:The Returned value needs to be manually wrapped asOptionalInstance, and parameter value cannot be empty.
Optional. of Nullable"Hello+World".flatMapt->{Ift.contaIns+{t=t.replace+,""}//ReturnOptional.oft}.IfPresentt->{System.Out.PrIntlnt}--HelloWorld
2.tenOrElse
OrElse .
Objectrs=Optional. of NullableNull.OrElse"Null"System.Out.PrIntlnrs--Null
2.11OrElseGet
The OrElseGet method Returns a non Null value if the Instance contaIns it; Otherwise, it will execute theSupplier.
Objectresult=Optional. of NullableNull.OrElseGet->{ReturnError;}System. OutPrIntlnresult--error
2.12OrElseThrow
OrElseThrow .
Optional. of NullableNull.OrElseThrow->NewRuntimeExceptionArgument is empty--ExceptionInthread"maIn"java.lang.RuntimeException:atcom.x.x.x.x.OptionalTest.lambda$maIn$tenOptionalTest3. java:one hundred and forty-fouratjava.util.Optional.OrElseThrowOptional. java:two hundred and ninety
How should Option be used
Optional . Optional Serializable.. Optional Jackson Optional Object.Jackson Null. jackson-modules-java8 .Optional .Optional Optional API.
Summary
The above is the newly added JDK8OptionalSummary of commonly used methods for classes, whereOf NullableMapandOrElse.
in additionOrElseOrElseGetOrElseThrowThe differences are as follows:
- OrElseIf the instance contains a null value, return the specified value passed in
- OrElseGetIf the instance contains a null value, return the returned value from the passed in method
- OrElseThrowIf the instance contains null values, return the specified exception type
adoptOptionalTo solve the problemNPEException code is more elegant, such as the current object being relatively simple, which is a simple judgmentobj != Null.
andand.
.
#Headline Creation Challenge # # Java#
Disclaimer: The content of this article is sourced from the internet. The copyright of the text, images, and other materials belongs to the original author. The platform reprints the materials for the purpose of conveying more information. The content of the article is for reference and learning only, and should not be used for commercial purposes. If it infringes on your legitimate rights and interests, please contact us promptly and we will handle it as soon as possible! We respect copyright and are committed to protecting it. Thank you for sharing.(Email:win-e@163.com)
Mobile advertising space rental |
Tag: Option is good thing that most people really don
Lack of social interaction in the elderly is associated with reduced Brain size
NextFuzhou Changle International Airport Comprehensive Bonded Zone approved
Guess you like
-
Chinese New Year Elements Sell Like Hotcakes Overseas: Cross-border E-commerce "Spring Festival Economy" Booms, Cainiao Overseas Warehouses Help Merchants Capture Market ShareDetail
2025-01-13 14:17:50 1
-
China Railway's 12306 System Successfully Navigates Spring Festival Travel RushDetail
2025-01-13 12:56:54 1
-
Handan, Hebei Province Successfully Tests First Low-Altitude Drone Delivery Route, Ushering in a New Era of Smart LogisticsDetail
2025-01-13 12:50:13 1
-
Kuaishou Leads in Developing Anti-Fraud Industry Standards, Contributing to a Secure and Reliable Short-Video CommunityDetail
2025-01-13 09:47:32 1
-
Microsoft Offers Top Salaries to Retain AI Talent: AI Software Engineers Earn Over $400,000 AnnuallyDetail
2025-01-12 17:28:34 1
- Detail
-
Chang'e-5 Mission Unveils Secrets: New Discoveries Regarding Lunar Magnetic Field Strength and Deep Dynamics 2 Billion Years AgoDetail
2025-01-10 11:42:44 1
-
SenseTime's "Day Day New" Multimodal Large Model: Native Fusion Enables Diverse ApplicationsDetail
2025-01-10 11:40:40 1
-
Cainiao International Express Expands Nationwide: Empowering Cross-Border SMEs and Building an Inclusive Logistics EcosystemDetail
2025-01-09 14:26:48 1
-
WeChat Work Launches Full Internationalization Support, Empowering Chinese Businesses to "Go Global" and Drive Digital Transformation WorldwideDetail
2025-01-09 14:25:32 1
-
ByteDance Accelerates its Overseas Short-Form Drama Market Expansion with the Launch of Melolo APP, Aiming for Global Digital Entertainment LeadershipDetail
2025-01-09 14:21:47 1
-
Xiaomi Officially Launches in South Korea: Online Store Opening January 15th, Featuring Xiaomi 14T SeriesDetail
2025-01-09 14:16:46 1
- Detail
-
Pinduoduo's "New Quality Supply" Strategy: Deep Integration of Merchant Rights Protection and High-Quality Development of Industrial ClustersDetail
2025-01-08 19:46:50 11
-
Haier Smart Home Rushes Aid to Tibet Earthquake Zone: A Three-Pronged Approach to Support Post-Disaster ReconstructionDetail
2025-01-08 15:14:27 1
-
Haier Achieves 16th Consecutive Year as Global Leader in Large Home Appliance Retail Sales: A Success Story Driven by Globalization, High-End Strategy, and Scenario-Based SolutionsDetail
2025-01-08 10:04:33 1
-
Bai Yue Fan Xing: iQiyi's Grounded Xianxia Drama Delivers a Dopamine-Fueled Visual FeastDetail
2025-01-07 23:30:34 1
- Detail
-
The 6th Industrial Internet Competition Concludes Successfully, Ushering in a New Era for High-Quality Development of the Digital EconomyDetail
2025-01-07 14:29:09 1
-
Zero One AI Denies Alibaba Acquisition Rumors, Focuses on Application Landing and Commercialization in 2025Detail
2025-01-07 09:31:46 1