阿里巴巴Java开发手册-使用JDK8的Opional类来防止出现NPE问题
生活随笔
收集整理的這篇文章主要介紹了
阿里巴巴Java开发手册-使用JDK8的Opional类来防止出现NPE问题
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
/*** https://www.baeldung.com/java-optional*/@Testpublic void optionalTest(){Peo peo = new Peo("weijie", 18);/*** of、ofNullable*///of 判斷peo是否為空,如果不為空程序繼續執行Optional<Peo> _of = Optional.of(peo);//程序直接拋出NullException
// Optional<Peo> _ofNull = Optional.of(null);//ofNullable 不管值是否為空仍然執行Optional<Peo> _ofNullable = Optional.ofNullable(null);//如果值不為NULL則返回true,否則,falseSystem.out.println("_of: " + _of.isPresent());System.out.println("_ofNullable: " + _ofNullable.isPresent());/*** orElse、orElseGet、orElseThroe*///orElse 餓漢式,不管b中值是否為空仍然會加載到內存當中,高并發場景慎用Peo _orElse = _ofNullable.orElse(peo);System.out.println("_orElse: " + _orElse);//orElseGet 懶漢式,當b中值為null才加載到內存當中Peo _orElseGet = _ofNullable.orElseGet(() -> peo);System.out.println("_orElseGet:" +_orElseGet);//orElseThrow 當值不存在時候返回一個異常Peo _orElseThrow = _ofNullable.orElseThrow(() -> new IllegalArgumentException());System.out.println("orElseThrow: " + _orElseThrow);/*** filter*///判斷值是否和另一個值相等,通常和isPresent()搭配使用Optional<Peo> _filter = _of.filter(p -> p.age == 18);System.out.println("_filter: " + _filter.isPresent());Optional<Peo> _filter2 = _of.filter(p -> p.age == 16);System.out.println("_filter: " + _filter2.isPresent());/*** map、flatMap*///map 如果optional中有值則傳入函數體獲取Optional特定值,否則返回空值Optional<Integer> _map = _of.map(Peo::getAge);boolean _age = _map.filter(age -> age >= 15).filter(age -> age <= 24).isPresent();System.out.println("_age: " + _age);//flatMap 該方法作用和map一樣,區別是方法返回值不同 People::getAge -> Optional<Integer>類型People people = new People("weijie", 25);Optional<Integer> _flatMap = Optional.ofNullable(people).flatMap(People::getAge);System.out.println("_flatMap: " + _flatMap.get());}
class Peo{String name;Integer age;public Peo(String name, Integer age) {this.name = name;this.age = age;}@Overridepublic String toString() {return "Peo{" +"name='" + name + '\'' +", age=" + age +'}';}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;}}class People{String name;Integer age;public People(String name, Integer age) {this.name = name;this.age = age;}public Optional<String> getName() {return Optional.ofNullable(name);}public void setName(String name) {this.name = name;}public Optional<Integer> getAge() {return Optional.ofNullable(age);}public void setAge(Integer age) {this.age = age;}}
總結
以上是生活随笔為你收集整理的阿里巴巴Java开发手册-使用JDK8的Opional类来防止出现NPE问题的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 查询数据库每天更新的数量
- 下一篇: ngnix 作用(通俗易懂)【转载】