java8的新特性有哪些(java,编程语言)

时间:2024-04-29 20:04:38 作者 : 石家庄SEO 分类 : 编程语言
  • TAG :

作为一名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类的组成如下图所示:

java8的新特性有哪些

java8的新特性有哪些

通过类上面的注释我们可知:这是一个可以为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的新特性有哪些的详细内容,希望对您有所帮助,信息来源于网络。
上一篇:如何解决sqlplus登录缓慢下一篇:

4 人围观 / 0 条评论 ↓快速评论↓

(必须)

(必须,保密)

阿狸1 阿狸2 阿狸3 阿狸4 阿狸5 阿狸6 阿狸7 阿狸8 阿狸9 阿狸10 阿狸11 阿狸12 阿狸13 阿狸14 阿狸15 阿狸16 阿狸17 阿狸18