java8的新特性有哪些
导读:本文共6047.5字符,通常情况下阅读需要20分钟。同时您也可以点击右侧朗读,来听本文内容。按键盘←(左) →(右) 方向键可以翻页。
摘要: 作为一名java开发人员,每个人都会遇到这样的问题:调用一个方法得到了返回值却不能直接将返回值作为参数去调用别的方法。我们首先要判断这个返回值是否为null,只有在非空的前提下才能将其作为其他方法的参数。否则就会出现NPE异常,就是传说中的空指针异常。举个例子:if(null==str){//空指针判定return0;}returnstr.length()... ...
目录
(为您整理了一些要点),点击可以直达。作为一名java开发人员,每个人都会遇到这样的问题:调用一个方法得到了返回值却不能直接将返回值作为参数去调用别的方法。我们首先要判断这个返回值是否为null,只有在非空的前提下才能将其作为其他方法的参数。否则就会出现NPE异常,就是传说中的空指针异常。
举个例子:
if(null==str){//空指针判定return0;}returnstr.length();//采用optionalreturnOptional.ofNullable(str).map(String::length).orElse(0);//再来个复杂点的publicStringisCheckUser(Useruser){if(null!=user){//获取角色if(null!=user.getRole()){//获取管理员权限if(null!=user.getRole().getPermission()){return"获取管理员权限";}}}else{return"用户为空";}}//使用optional类publicStringisCheckUser(Useruser){returnOptional.ofNullable(user).map(u->u.getRole).map(p->p.getPermission()).orElse("用户为空");}
本文将根据java8新特性Optional类源码来逐步分析以及教会大家如何使用Optional类去优雅的判断是否为null。
optional类的组成如下图所示:
通过类上面的注释我们可知:这是一个可以为null或者不为null的容器对象。如果值存在则isPresent()方法会返回true,调用get()方法会返回该对象。
接下来将会为大家逐个探讨Optional类里面的方法,并举例说明。
of
源码:/***Returnsan{@codeOptional}withthespecifiedpresentnon-nullvalue.**@param<T>theclassofthevalue*@paramvaluethevaluetobepresent,whichmustbenon-null*@returnan{@codeOptional}withthevaluepresent*@throwsNullPointerExceptionifvalueisnull*/publicstatic<T>Optional<T>of(Tvalue){returnnewOptional<>(value);}
通过源码注释可知,该方法会返回一个不会null的optional对象,如果value为null的话则会抛出NullPointerException异常。
实例如下:
//调用工厂方法创建Optional实例Optional<String>name=Optional.of("javaHuang");//传入参数为null,抛出NullPointerException.Optional<String>nullValue=Optional.of(null);
ofNullable
源码:/***Returnsan{@codeOptional}describingthespecifiedvalue,ifnon-null,*otherwisereturnsanempty{@codeOptional}.**@param<T>theclassofthevalue*@paramvaluethepossibly-nullvaluetodescribe*@returnan{@codeOptional}withapresentvalueifthespecifiedvalue*isnon-null,otherwiseanempty{@codeOptional}*/publicstatic<T>Optional<T>ofNullable(Tvalue){returnvalue==null?empty():of(value);}
通过注释可以知道:当value不为null时会返回一个optional对象,如果value为null的时候,则会返回一个空的optional对象。
实例如下:
//返回空的optional对象OptionalemptyValue=Optional.ofNullable(null);or//返回name为“javaHuang”的optional对象Optionalname=Optional.ofNullable("javaHuang");
isPresent
源码:/***Return{@codetrue}ifthereisavaluepresent,otherwise{@codefalse}.**@return{@codetrue}ifthereisavaluepresent,otherwise{@codefalse}*/publicbooleanisPresent(){returnvalue!=null;}
通过注释可以知道:如果值为null返回false,不为null返回true。
实例如下:
if(name.isPresent()){System.out.println(name.get());//输出javaHuang}emptyValue.isPresent()==false
get
源码:/***Ifavalueispresentinthis{@codeOptional},returnsthevalue,*otherwisethrows{@codeNoSuchElementException}.**@returnthenon-nullvalueheldbythis{@codeOptional}*@throwsNoSuchElementExceptionifthereisnovaluepresent**@seeOptional#isPresent()*/publicTget(){if(value==null){thrownewNoSuchElementException("Novaluepresent");}returnvalue;}
通过注释可以知道:如果value不为null的话,返回一个optional对象,如果value为null的话,抛出NoSuchElementException异常
实例如下:
try{System.out.println(emptyValue.get());}catch(NoSuchElementExceptionex){System.err.println(ex.getMessage());}
ifPresent
源码:/***Ifavalueispresent,invokethespecifiedconsumerwiththevalue,*otherwisedonothing.**@paramconsumerblocktobeexecutedifavalueispresent*@throwsNullPointerExceptionifvalueispresentand{@codeconsumer}is*null*/publicvoidifPresent(Consumer<?superT>consumer){if(value!=null)consumer.accept(value);}
通过源码可以知道:如果Optional实例有值则为其调用consumer,否则不做处理
实例如下:
name.ifPresent((value)->{System.out.println("Hisnameis:"+value);});//打印HisnameisjavaHuang
orElse
源码:/***Returnthevalueifpresent,otherwisereturn{@codeother}.**@paramotherthevaluetobereturnedifthereisnovaluepresent,may*benull*@returnthevalue,ifpresent,otherwise{@codeother}*/publicTorElse(Tother){returnvalue!=null?value:other;}
通过注释可以知道:如果value不为null的话直接返回value,否则返回传入的other值。
实例如下:
System.out.println(empty.orElse("Thereisnovaluepresent!"));//返回:Thereisnovaluepresent!System.out.println(name.orElse("Thereissomevalue!"));//返回:javaHuang
orElseGet
源码:/***Returnthevalueifpresent,otherwiseinvoke{@codeother}andreturn*theresultofthatinvocation.**@paramothera{@codeSupplier}whoseresultisreturnedifnovalue*ispresent*@returnthevalueifpresentotherwisetheresultof{@codeother.get()}*@throwsNullPointerExceptionifvalueisnotpresentand{@codeother}is*null*/publicTorElseGet(Supplier<?extendsT>other){returnvalue!=null?value:other.get();}
通过注释可以知道:orElseGet与orElse方法类似,区别在于得到的默认值。orElse方法将传入的字符串作为默认值,orElseGet方法可以接受Supplier接口的实现用来生成默认值
实例如下:
System.out.println(empty.orElseGet(()->"DefaultValue"));System.out.println(name.orElseGet(String::new));
orElseThrow
源码:/***Returnthecontainedvalue,ifpresent,otherwisethrowanexception*tobecreatedbytheprovidedsupplier.**@apiNoteAmethodreferencetotheexceptionconstructorwithanempty*argumentlistcanbeusedasthesupplier.Forexample,*{@codeIllegalStateException::new}**@param<X>Typeoftheexceptiontobethrown*@paramexceptionSupplierThesupplierwhichwillreturntheexceptionto*bethrown*@returnthepresentvalue*@throwsXifthereisnovaluepresent*@throwsNullPointerExceptionifnovalueispresentand*{@codeexceptionSupplier}isnull*/public<XextendsThrowable>TorElseThrow(Supplier<?extendsX>exceptionSupplier)throwsX{if(value!=null){returnvalue;}else{throwexceptionSupplier.get();}}
通过注释可以得知:如果有值则将其返回,否则抛出supplier接口创建的异常。
实例如下:
try{empty.orElseThrow(IllegalArgumentException::new);}catch(Throwableex){System.out.println("error:"+ex.getMessage());}
map
源码:/***Ifavalueispresent,applytheprovidedmappingfunctiontoit,*andiftheresultisnon-null,returnan{@codeOptional}describingthe*result.Otherwisereturnanempty{@codeOptional}.**@apiNoteThismethodsupportspost-processingonoptionalvalues,without*theneedtoexplicitlycheckforareturnstatus.Forexample,the*followingcodetraversesastreamoffilenames,selectsonethathas*notyetbeenprocessed,andthenopensthatfile,returningan*{@codeOptional<FileInputStream>}:**<pre>{@code*Optional<FileInputStream>fis=*names.stream().filter(name->!isProcessedYet(name))*.findFirst()*.map(name->newFileInputStream(name));*}</pre>**Here,{@codefindFirst}returnsan{@codeOptional<String>},andthen*{@codemap}returnsan{@codeOptional<FileInputStream>}forthedesired*fileifoneexists.**@param<U>Thetypeoftheresultofthemappingfunction*@parammapperamappingfunctiontoapplytothevalue,ifpresent*@returnan{@codeOptional}describingtheresultofapplyingamapping*functiontothevalueofthis{@codeOptional},ifavalueispresent,*otherwiseanempty{@codeOptional}*@throwsNullPointerExceptionifthemappingfunctionisnull*/public<U>Optional<U>map(Function<?superT,?extendsU>mapper){Objects.requireNonNull(mapper);if(!isPresent())returnempty();else{returnOptional.ofNullable(mapper.apply(value));}}
通过代码可以得知:如果有值,则对其执行调用mapping函数得到返回值。如果返回值不为null,则创建包含mapping返回值的Optional作为map方法返回值,否则返回空Optional。
实例如下:
Optional<String>upperName=name.map((value)->value.toUpperCase());System.out.println(upperName.orElse("empty"));
flatMap
源码:/***Ifavalueispresent,applytheprovided{@codeOptional}-bearing*mappingfunctiontoit,returnthatresult,otherwisereturnanempty*{@codeOptional}.Thismethodissimilarto{@link#map(Function)},*buttheprovidedmapperisonewhoseresultisalreadyan{@codeOptional},*andifinvoked,{@codeflatMap}doesnotwrapitwithanadditional*{@codeOptional}.**@param<U>Thetypeparametertothe{@codeOptional}returnedby*@parammapperamappingfunctiontoapplytothevalue,ifpresent*themappingfunction*@returntheresultofapplyingan{@codeOptional}-bearingmapping*functiontothevalueofthis{@codeOptional},ifavalueispresent,*otherwiseanempty{@codeOptional}*@throwsNullPointerExceptionifthemappingfunctionisnullorreturns*anullresult*/public<U>Optional<U>flatMap(Function<?superT,Optional<U>>mapper){Objects.requireNonNull(mapper);if(!isPresent())returnempty();else{returnObjects.requireNonNull(mapper.apply(value));}}
通过注释可以得知:如果有值,为其执行mapping函数返回Optional类型返回值,否则返回空Optional。
实例如下:
upperName=name.flatMap((value)->Optional.of(value.toUpperCase()));System.out.println(upperName.get());
filter
源码:/***Ifavalueispresent,andthevaluematchesthegivenpredicate,*returnan{@codeOptional}describingthevalue,otherwisereturnan*empty{@codeOptional}.**@parampredicateapredicatetoapplytothevalue,ifpresent*@returnan{@codeOptional}describingthevalueofthis{@codeOptional}*ifavalueispresentandthevaluematchesthegivenpredicate,*otherwiseanempty{@codeOptional}*@throwsNullPointerExceptionifthepredicateisnull*/publicOptional<T>filter(Predicate<?superT>predicate){Objects.requireNonNull(predicate);if(!isPresent())returnthis;elsereturnpredicate.test(value)?this:empty();}
通过代码可以得知:如果有值并且满足断言条件返回包含该值的Optional,否则返回空Optional。
实例如下:
List<String>names=Arrays.asList("javaHuang","tony");for(Strings:names){Optional<String>nameLenLessThan7=Optional.of(s).filter((value)->"tony".equals(value));System.out.println(nameLenLessThan7.orElse("ThenameisjavaHuang"));}
</div> <div class="zixun-tj-product adv-bottom"></div> </div> </div> <div class="prve-next-news">
java8的新特性有哪些的详细内容,希望对您有所帮助,信息来源于网络。