1. 程式人生 > >Java 中遇到null 和為空的情況,使用Optional來解決。

Java 中遇到null 和為空的情況,使用Optional來解決。

best found getname may short tst orelse AS eof

Java 中遇到null 和為空的情況,使用Optional來解決

示例代碼:

 1 package crazy;
 2 
 3 import java.util.Optional;
 4 
 5 class Company {
 6     private String name;
 7     private Optional<Office> office;
 8 
 9     public Company(String name, Optional<Office> office) {
10         this.name = name;
11         this
.office = office; 12 } 13 14 public String getName() { 15 return name; 16 } 17 18 public Optional<Office> getOffice() { 19 return office; 20 } 21 } 22 23 class Office { 24 private String id; 25 private Optional<Address> address; 26 27 public
Office(String id, Optional<Address> address) { 28 this.id = id; 29 this.address = address; 30 } 31 32 public String getId() { 33 return id; 34 } 35 36 public Optional<Address> getAddress() { 37 return address; 38 } 39 } 40 41 class Address {
42 private Optional<String> street; 43 private Optional<String> city; 44 45 public Address(Optional<String> street, Optional<String> city) { 46 this.street = street; 47 this.city = city; 48 } 49 50 public Optional<String> getStreet() { 51 return street; 52 } 53 54 public Optional<String> getCity() { 55 return city; 56 } 57 } 58 59 public class OptionalDemo1 { 60 61 public static void main(String[] args) { 62 Optional<Address> address1 = Optional.of(new Address(Optional.ofNullable(null), Optional.of("New York"))); 63 Optional<Office> office1 = Optional.of(new Office("OF1", address1)); 64 Optional<Company> company1 = Optional.of(new Company("Door Never Closed", office1)); 65 66 // What is the street address of company1? 67 // In which city company1 is located? 68 Optional<Office> maybeOffice = company1.flatMap(Company::getOffice); 69 Optional<Address> maybeAddress = office1.flatMap(Office::getAddress); 70 Optional<String> maybeStreet = address1.flatMap(Address::getStreet); 71 72 maybeStreet.ifPresent(System.out::println); 73 if (maybeStreet.isPresent()) { 74 System.out.println(maybeStreet.get()); 75 } else { 76 System.out.println("Street not found."); 77 } 78 79 // shorter way 80 String city = company1.flatMap(Company::getOffice) 81 .flatMap(Office::getAddress) 82 .flatMap(Address::getStreet) 83 .orElse("City is not found."); 84 85 System.out.println("City: " + city); 86 87 // only print if city is not null 88 company1.flatMap(Company::getOffice) 89 .flatMap(Office::getAddress) 90 .flatMap(Address::getCity) 91 .ifPresent(System.out::println); 92 93 } 94 }

talk is easy ,show you the code

歡迎關註:一只阿木木

Java 中遇到null 和為空的情況,使用Optional來解決。