這篇文章主要講解了“java8的新特性有哪些”,文中的講解內(nèi)容簡(jiǎn)單清晰,易于學(xué)習(xí)與理解,下面請(qǐng)大家跟著小編的思路慢慢深入,一起來(lái)研究和學(xué)習(xí)“java8的新特性有哪些”吧!
渝水網(wǎng)站建設(shè)公司創(chuàng)新互聯(lián),渝水網(wǎng)站設(shè)計(jì)制作,有大型網(wǎng)站制作公司豐富經(jīng)驗(yàn)。已為渝水成百上千家提供企業(yè)網(wǎng)站建設(shè)服務(wù)。企業(yè)網(wǎng)站搭建\成都外貿(mào)網(wǎng)站制作要多少錢(qián),請(qǐng)找那個(gè)售后服務(wù)好的渝水做網(wǎng)站的公司定做!
作為一名java開(kāi)發(fā)人員,每個(gè)人都會(huì)遇到這樣的問(wèn)題:調(diào)用一個(gè)方法得到了返回值卻不能直接將返回值作為參數(shù)去調(diào)用別的方法。我們首先要判斷這個(gè)返回值是否為null,只有在非空的前提下才能將其作為其他方法的參數(shù)。否則就會(huì)出現(xiàn)NPE異常,就是傳說(shuō)中的空指針異常。
舉個(gè)例子:
if(null == str) { // 空指針判定 return 0; } return str.length(); //采用optional return Optional.ofNullable(str).map(String::length).orElse(0); //再來(lái)個(gè)復(fù)雜點(diǎn)的 public String isCheckUser(User user){ if(null != user){ // 獲取角色 if(null != user.getRole()){ // 獲取管理員權(quán)限 if(null != user.getRole().getPermission()){ return "獲取管理員權(quán)限"; } } }else{ return "用戶為空"; } } //使用optional類 public String isCheckUser(User user){ return Optional.ofNullable(user) .map(u -> u.getRole) .map(p -> p.getPermission()) .orElse("用戶為空"); }
本文將根據(jù)java8新特性O(shè)ptional類源碼來(lái)逐步分析以及教會(huì)大家如何使用Optional類去優(yōu)雅的判斷是否為null。
optional類的組成如下圖所示:
通過(guò)類上面的注釋我們可知:這是一個(gè)可以為null或者不為null的容器對(duì)象。如果值存在則isPresent()方法會(huì)返回true,調(diào)用get()方法會(huì)返回該對(duì)象。
接下來(lái)將會(huì)為大家逐個(gè)探討Optional類里面的方法,并舉例說(shuō)明。
of
源碼: /** * Returns an {@code Optional} with the specified present non-null value. * * @paramthe class of the value * @param value the value to be present, which must be non-null * @return an {@code Optional} with the value present * @throws NullPointerException if value is null */ public static Optional of(T value) { return new Optional<>(value); }
通過(guò)源碼注釋可知,該方法會(huì)返回一個(gè)不會(huì)null的optional對(duì)象,如果value為null的話則會(huì)拋出NullPointerException 異常。
實(shí)例如下:
//調(diào)用工廠方法創(chuàng)建Optional實(shí)例 Optionalname = Optional.of("javaHuang"); //傳入?yún)?shù)為null,拋出NullPointerException. Optional nullValue= Optional.of(null);
ofNullable
源碼: /** * Returns an {@code Optional} describing the specified value, if non-null, * otherwise returns an empty {@code Optional}. * * @paramthe class of the value * @param value the possibly-null value to describe * @return an {@code Optional} with a present value if the specified value * is non-null, otherwise an empty {@code Optional} */ public static Optional ofNullable(T value) { return value == null ? empty() : of(value); }
通過(guò)注釋可以知道:當(dāng)value不為null時(shí)會(huì)返回一個(gè)optional對(duì)象,如果value為null的時(shí)候,則會(huì)返回一個(gè)空的optional對(duì)象。
實(shí)例如下:
//返回空的optional對(duì)象 Optional emptyValue = Optional.ofNullable(null); or //返回name為“javaHuang”的optional對(duì)象 Optional name= Optional.ofNullable("javaHuang");
isPresent
源碼: /** * Return {@code true} if there is a value present, otherwise {@code false}. * * @return {@code true} if there is a value present, otherwise {@code false} */ public boolean isPresent() { return value != null; }
通過(guò)注釋可以知道:如果值為null返回false,不為null返回true。
實(shí)例如下:
if (name.isPresent()) { System.out.println(name.get());//輸出javaHuang } emptyValue.isPresent()==false
get
源碼: /** * If a value is present in this {@code Optional}, returns the value, * otherwise throws {@code NoSuchElementException}. * * @return the non-null value held by this {@code Optional} * @throws NoSuchElementException if there is no value present * * @see Optional#isPresent() */ public T get() { if (value == null) { throw new NoSuchElementException("No value present"); } return value; }
通過(guò)注釋可以知道:如果value不為null的話,返回一個(gè)optional對(duì)象,如果value為null的話,拋出NoSuchElementException異常
實(shí)例如下:
try { System.out.println(emptyValue.get()); } catch (NoSuchElementException ex) { System.err.println(ex.getMessage()); }
ifPresent
源碼: /** * If a value is present, invoke the specified consumer with the value, * otherwise do nothing. * * @param consumer block to be executed if a value is present * @throws NullPointerException if value is present and {@code consumer} is * null */ public void ifPresent(Consumer super T> consumer) { if (value != null) consumer.accept(value); }
通過(guò)源碼可以知道:如果Optional實(shí)例有值則為其調(diào)用consumer,否則不做處理
實(shí)例如下:
name.ifPresent((value) -> { System.out.println("His name is: " + value); }); //打印 His name is javaHuang
orElse
源碼: /** * Return the value if present, otherwise return {@code other}. * * @param other the value to be returned if there is no value present, may * be null * @return the value, if present, otherwise {@code other} */ public T orElse(T other) { return value != null ? value : other; }
通過(guò)注釋可以知道:如果value不為null的話直接返回value,否則返回傳入的other值。
實(shí)例如下:
System.out.println(empty.orElse("There is no value present!")); //返回:There is no value present! System.out.println(name.orElse("There is some value!")); //返回:javaHuang
orElseGet
源碼: /** * Return the value if present, otherwise invoke {@code other} and return * the result of that invocation. * * @param other a {@code Supplier} whose result is returned if no value * is present * @return the value if present otherwise the result of {@code other.get()} * @throws NullPointerException if value is not present and {@code other} is * null */ public T orElseGet(Supplier extends T> other) { return value != null ? value : other.get(); }
通過(guò)注釋可以知道:orElseGet與orElse方法類似,區(qū)別在于得到的默認(rèn)值。orElse方法將傳入的字符串作為默認(rèn)值,orElseGet方法可以接受Supplier接口的實(shí)現(xiàn)用來(lái)生成默認(rèn)值
實(shí)例如下:
System.out.println(empty.orElseGet(() -> "Default Value")); System.out.println(name.orElseGet(String::new));
orElseThrow
源碼: /** * Return the contained value, if present, otherwise throw an exception * to be created by the provided supplier. * * @apiNote A method reference to the exception constructor with an empty * argument list can be used as the supplier. For example, * {@code IllegalStateException::new} * * @paramType of the exception to be thrown * @param exceptionSupplier The supplier which will return the exception to * be thrown * @return the present value * @throws X if there is no value present * @throws NullPointerException if no value is present and * {@code exceptionSupplier} is null */ public T orElseThrow(Supplier extends X> exceptionSupplier) throws X { if (value != null) { return value; } else { throw exceptionSupplier.get(); } }
通過(guò)注釋可以得知:如果有值則將其返回,否則拋出supplier接口創(chuàng)建的異常。
實(shí)例如下:
try { empty.orElseThrow(IllegalArgumentException::new); } catch (Throwable ex) { System.out.println("error:" + ex.getMessage()); }
map
源碼: /** * If a value is present, apply the provided mapping function to it, * and if the result is non-null, return an {@code Optional} describing the * result. Otherwise return an empty {@code Optional}. * * @apiNote This method supports post-processing on optional values, without * the need to explicitly check for a return status. For example, the * following code traverses a stream of file names, selects one that has * not yet been processed, and then opens that file, returning an * {@code Optional}: * * {@code * Optional* * Here, {@code findFirst} returns an {@code Optionalfis = * names.stream().filter(name -> !isProcessedYet(name)) * .findFirst() * .map(name -> new FileInputStream(name)); * } }, and then * {@code map} returns an {@code Optional } for the desired * file if one exists. * * @param The type of the result of the mapping function * @param mapper a mapping function to apply to the value, if present * @return an {@code Optional} describing the result of applying a mapping * function to the value of this {@code Optional}, if a value is present, * otherwise an empty {@code Optional} * @throws NullPointerException if the mapping function is null */ public Optional map(Function super T, ? extends U> mapper) { Objects.requireNonNull(mapper); if (!isPresent()) return empty(); else { return Optional.ofNullable(mapper.apply(value)); } }
通過(guò)代碼可以得知:如果有值,則對(duì)其執(zhí)行調(diào)用mapping函數(shù)得到返回值。如果返回值不為null,則創(chuàng)建包含mapping返回值的Optional作為map方法返回值,否則返回空Optional。
實(shí)例如下:
OptionalupperName = name.map((value) -> value.toUpperCase()); System.out.println(upperName.orElse("empty"));
flatMap
源碼: /** * If a value is present, apply the provided {@code Optional}-bearing * mapping function to it, return that result, otherwise return an empty * {@code Optional}. This method is similar to {@link #map(Function)}, * but the provided mapper is one whose result is already an {@code Optional}, * and if invoked, {@code flatMap} does not wrap it with an additional * {@code Optional}. * * @param The type parameter to the {@code Optional} returned by * @param mapper a mapping function to apply to the value, if present * the mapping function * @return the result of applying an {@code Optional}-bearing mapping * function to the value of this {@code Optional}, if a value is present, * otherwise an empty {@code Optional} * @throws NullPointerException if the mapping function is null or returns * a null result */ public Optional flatMap(Function super T, Optional> mapper) { Objects.requireNonNull(mapper); if (!isPresent()) return empty(); else { return Objects.requireNonNull(mapper.apply(value)); } }
通過(guò)注釋可以得知:如果有值,為其執(zhí)行mapping函數(shù)返回Optional類型返回值,否則返回空Optional。
實(shí)例如下:
upperName = name.flatMap((value) -> Optional.of(value.toUpperCase())); System.out.println(upperName.get());
filter
源碼: /** * If a value is present, and the value matches the given predicate, * return an {@code Optional} describing the value, otherwise return an * empty {@code Optional}. * * @param predicate a predicate to apply to the value, if present * @return an {@code Optional} describing the value of this {@code Optional} * if a value is present and the value matches the given predicate, * otherwise an empty {@code Optional} * @throws NullPointerException if the predicate is null */ public Optionalfilter(Predicate super T> predicate) { Objects.requireNonNull(predicate); if (!isPresent()) return this; else return predicate.test(value) ? this : empty(); }
通過(guò)代碼可以得知:如果有值并且滿足斷言條件返回包含該值的Optional,否則返回空Optional。
實(shí)例如下:
Listnames = Arrays.asList("javaHuang","tony"); for(String s:names) { Optional nameLenLessThan7 = Optional.of(s).filter((value) -> "tony".equals(value)); System.out.println(nameLenLessThan7.orElse("The name is javaHuang")); }
感謝各位的閱讀,以上就是“java8的新特性有哪些”的內(nèi)容了,經(jīng)過(guò)本文的學(xué)習(xí)后,相信大家對(duì)java8的新特性有哪些這一問(wèn)題有了更深刻的體會(huì),具體使用情況還需要大家實(shí)踐驗(yàn)證。這里是創(chuàng)新互聯(lián),小編將為大家推送更多相關(guān)知識(shí)點(diǎn)的文章,歡迎關(guān)注!