答應(yīng)我,別再靠!= null走天下了可以嗎?
這里是碼農(nóng)充電第一站,回復(fù)“666”,獲取一份專屬大禮包 真愛,請(qǐng)?jiān)O(shè)置“星標(biāo)”或點(diǎn)個(gè)“在看”
常規(guī)判斷://對(duì)象 人//屬性有 name,agePerson person=new Person();if (null==person){return "person為null";}return person;
使用Optional://對(duì)象 人//屬性有 name,agePerson person=new Person();return Optional.ofNullable(person).orElse("person為null");
public class Person {private String name;private Integer age;public Person(String name, Integer age) {this.name = name;this.age = age;????}public Person() {}public String getName() {return name;}public void setName(String name) {this.name = name;}public Integer getAge() {return age;}public void setAge(Integer age) {this.age = age;}}
public final class Optional{ private static final Optional> EMPTY = new Optional<>();private final T value;//我們可以看到兩個(gè)構(gòu)造方格都是private 私有的//說明 我們沒辦法在外面去new出來Optional對(duì)象private Optional() {this.value = null;}private Optional(T value) {this.value = Objects.requireNonNull(value);}//這個(gè)靜態(tài)方法大致 是創(chuàng)建出一個(gè)包裝值為空的一個(gè)對(duì)象因?yàn)闆]有任何參數(shù)賦值public staticOptional empty() { @SuppressWarnings("unchecked")Optionalt = (Optional ) EMPTY; return t;}//這個(gè)靜態(tài)方法大致 是創(chuàng)建出一個(gè)包裝值非空的一個(gè)對(duì)象 因?yàn)樽隽速x值public staticOptional of(T value) { return new Optional<>(value);}//這個(gè)靜態(tài)方法大致是 如果參數(shù)value為空,則創(chuàng)建空對(duì)象,如果不為空,則創(chuàng)建有參對(duì)象public staticOptional ofNullable(T value) { return value == null ? empty() : of(value);}}
// 1、創(chuàng)建一個(gè)包裝對(duì)象值為空的Optional對(duì)象OptionaloptEmpty = Optional.empty(); // 2、創(chuàng)建包裝對(duì)象值非空的Optional對(duì)象OptionaloptOf = Optional.of("optional"); // 3、創(chuàng)建包裝對(duì)象值允許為空也可以不為空的Optional對(duì)象OptionaloptOfNullable1 = Optional.ofNullable(null); OptionaloptOfNullable2 = Optional.ofNullable("optional");
public T get() {if (value == null) {throw new NoSuchElementException("No value present");}return value;}
Person person=new Person();person.setAge(2);Optional.ofNullable(person).get();
public boolean isPresent() {return value != null;}
Person person=new Person();person.setAge(2);if (Optional.ofNullable(person).isPresent()){//寫不為空的邏輯System.out.println("不為空");}else{//寫為空的邏輯System.out.println("為空");}
public void ifPresent(Consumer super T> consumer) {//如果value不為空,則運(yùn)行accept方法體if (value != null)consumer.accept(value);}
Person person=new Person();person.setAge(2);Optional.ofNullable(person).ifPresent(p -> System.out.println("年齡"+p.getAge()));
public Optionalfilter(Predicate super T> predicate) { Objects.requireNonNull(predicate);//如果為空直接返回thisif (!isPresent())return this;else//判斷返回本身還是空Optionalreturn predicate.test(value) ? this : empty();}
Person person=new Person();person.setAge(2);Optional.ofNullable(person).filter(p -> p.getAge()>50);
public Optional map(Function super T, ? extends U> mapper) {Objects.requireNonNull(mapper);//如果為空返回自己if (!isPresent())return empty();else {//否則返回用方法修飾過的Optionalreturn Optional.ofNullable(mapper.apply(value));}}
Person person1=new Person();person.setAge(2);String optName = Optional.ofNullable(person).map(p -> person.getName()).orElse("name為空");
public Optional flatMap(Function super T, Optional> mapper) {Objects.requireNonNull(mapper);if (!isPresent())return empty();else {return Objects.requireNonNull(mapper.apply(value));}}
Person person=new Person();person.setAge(2);Optional
public T orElse(T other) {//如果非空,返回value,如果為空,返回otherreturn value != null ? value : other;}
Person person1=new Person();person.setAge(2);Optional.ofNullable(person).orElse(new Person("小明", 2));
public T orElseGet(Supplier extends T> other) {return value != null ? value : other.get();}
Optional> sup=Optional.ofNullable(Person::new); //調(diào)用get()方法,此時(shí)才會(huì)調(diào)用對(duì)象的構(gòu)造方法,即獲得到真正對(duì)象Optional.ofNullable(person).orElseGet(sup.get());
publicT orElseThrow(Supplier extends X> exceptionSupplier) throws X { if (value != null) {return value;} else {throw exceptionSupplier.get();}}
//簡單的一個(gè)查詢Member member = memberService.selectByPhone(request.getPhone());Optional.ofNullable(member).orElseThrow(() -> new ServiceException("沒有查詢的相關(guān)數(shù)據(jù)"));
//查詢一個(gè)對(duì)象Member member = memberService.selectByIdNo(request.getCertificateNo());//使用ofNullable加orElseThrow做判斷和操作Optional.ofNullable(member).orElseThrow(() -> new ServiceException("沒有查詢的相關(guān)數(shù)據(jù)"));
public interface LocationRepository extends JpaRepository{ OptionalfindLocationById(String id); }
public TerminalVO findById(String id) {//這個(gè)方法在dao層也是用了Optional包裝了OptionalterminalOptional = terminalRepository.findById(id); //直接使用isPresent()判斷是否為空if (terminalOptional.isPresent()) {//使用get()方法獲取對(duì)象值Terminal terminal = terminalOptional.get();//在實(shí)戰(zhàn)中,我們已經(jīng)免去了用set去賦值的繁瑣,直接用BeanCopy去賦值TerminalVO terminalVO = BeanCopyUtils.copyBean(terminal, TerminalVO.class);//調(diào)用dao層方法返回包裝后的對(duì)象Optionallocation = locationRepository.findLocationById(terminal.getLocationId()); if (location.isPresent()) {terminalVO.setFullName(location.get().getFullName());}return terminalVO;}//不要忘記拋出異常throw new ServiceException("該終端不存在");}
Person person=new Person();person.setName("");persion.setAge(2);//普通判斷if(StringUtils.isNotBlank(person.getName())){//名稱不為空?qǐng)?zhí)行代碼塊}//使用Optional做判斷Optional.ofNullable(person).map(p -> p.getName()).orElse("name為空");
(完)
碼農(nóng)突圍資料鏈接
1、臥槽!字節(jié)跳動(dòng)《算法中文手冊(cè)》火了,完整版 PDF 開放下載!
2、計(jì)算機(jī)基礎(chǔ)知識(shí)總結(jié)與操作系統(tǒng) PDF 下載
3、艾瑪,終于來了!《LeetCode Java版題解》.PDF
4、Github 10K+,《LeetCode刷題C/C++版答案》出爐.PDF歡迎添加魚哥個(gè)人微信:smartfish2020,進(jìn)粉絲群或圍觀朋友圈。
評(píng)論
圖片
表情

