If null and empty are encountered in Java, use optional to resolve
Example code:
1 PackageCrazy;2 3 Importjava.util.Optional;4 5 classCompany {6 PrivateString name;7 PrivateOptional<office>Office;8 9 PublicCompany (String name, optional<office>Office) {Ten This. Name =name; One This. Office =Office; A } - - PublicString GetName () { the returnname; - } - - PublicOptional<office>Getoffice () { + returnOffice; - } + } A at classOffice { - PrivateString ID; - PrivateOptional<address>address; - - PublicOffice (String ID, optional<address>address) { - This. ID =ID; in This. Address =address; - } to + PublicString getId () { - returnID; the } * $ PublicOptional<address>getaddress () {Panax Notoginseng returnaddress; - } the } + A classAddress { the PrivateOptional<string>Street; + PrivateOptional<string>City ; - $ PublicAddress (Optional<string> Street, optional<string>City ) { $ This. Street =Street; - This. City =City ; - } the - PublicOptional<string>Getstreet () {Wuyi returnStreet; the } - Wu PublicOptional<string>getcity () { - returnCity ; About } $ } - - Public classOptionalDemo1 { - A Public Static voidMain (string[] args) { +optional<address> Address1 = Optional.of (NewAddress (Optional.ofnullable (NULL), Optional.of ("New York"))); theoptional<office> Office1 = Optional.of (NewOffice ("OF1", Address1)); -optional<company> company1 = Optional.of (NewCompany ("Door never Closed", Office1)); $ the //What is the street address of Company1? the //In which city Company1 is located? theOptional<office> Maybeoffice =Company1.flatmap (company::getoffice); theOptional<address> maybeaddress =Office1.flatmap (office::getaddress); -Optional<string> Maybestreet =Address1.flatmap (address::getstreet); in the maybestreet.ifpresent (system.out::p rintln); the if(Maybestreet.ispresent ()) { About System.out.println (Maybestreet.get ()); the}Else { theSystem.out.println ("Street not found.")); the } + - //Shorter theString City =Company1.flatmap (Company::getoffice)Bayi . FlatMap (office::getaddress) the . FlatMap (Address::getstreet) the. OrElse ("City was not found."); - -System.out.println ("City:" +City ); the the //Only print if city isn't null the Company1.flatmap (Company::getoffice) the . FlatMap (office::getaddress) - . FlatMap (address::getcity) the . Ifpresent (system.out::p rintln); the the }94}
Talk was easy and show you the code
Welcome attention: A Amumu
In Java, if NULL and NULL are encountered, use optional to resolve the situation.