您好,登錄后才能下訂單哦!
這篇文章主要講解了“java8的新特性有哪些”,文中的講解內容簡單清晰,易于學習與理解,下面請大家跟著小編的思路慢慢深入,一起來研究和學習“java8的新特性有哪些”吧!
作為一名java開發人員,每個人都會遇到這樣的問題:調用一個方法得到了返回值卻不能直接將返回值作為參數去調用別的方法。我們首先要判斷這個返回值是否為null,只有在非空的前提下才能將其作為其他方法的參數。否則就會出現NPE異常,就是傳說中的空指針異常。
舉個例子:
if(null == str) { // 空指針判定 return 0; } return str.length(); //采用optional return Optional.ofNullable(str).map(String::length).orElse(0); //再來個復雜點的 public String isCheckUser(User user){ if(null != user){ // 獲取角色 if(null != user.getRole()){ // 獲取管理員權限 if(null != user.getRole().getPermission()){ return "獲取管理員權限"; } } }else{ return "用戶為空"; } } //使用optional類 public String isCheckUser(User user){ return Optional.ofNullable(user) .map(u -> u.getRole) .map(p -> p.getPermission()) .orElse("用戶為空"); }
本文將根據java8新特性Optional類源碼來逐步分析以及教會大家如何使用Optional類去優雅的判斷是否為null。
optional類的組成如下圖所示:
通過類上面的注釋我們可知:這是一個可以為null或者不為null的容器對象。如果值存在則isPresent()方法會返回true,調用get()方法會返回該對象。
接下來將會為大家逐個探討Optional類里面的方法,并舉例說明。
of
源碼: /** * Returns an {@code Optional} with the specified present non-null value. * * @param <T> the 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 <T> Optional<T> of(T value) { return new Optional<>(value); }
通過源碼注釋可知,該方法會返回一個不會null的optional對象,如果value為null的話則會拋出NullPointerException 異常。
實例如下:
//調用工廠方法創建Optional實例 Optional<String> name = Optional.of("javaHuang"); //傳入參數為null,拋出NullPointerException. Optional<String> nullValue= Optional.of(null);
ofNullable
源碼: /** * Returns an {@code Optional} describing the specified value, if non-null, * otherwise returns an empty {@code Optional}. * * @param <T> the 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 <T> Optional<T> ofNullable(T value) { return value == null ? empty() : of(value); }
通過注釋可以知道:當value不為null時會返回一個optional對象,如果value為null的時候,則會返回一個空的optional對象。
實例如下:
//返回空的optional對象 Optional emptyValue = Optional.ofNullable(null); or //返回name為“javaHuang”的optional對象 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; }
通過注釋可以知道:如果值為null返回false,不為null返回true。
實例如下:
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; }
通過注釋可以知道:如果value不為null的話,返回一個optional對象,如果value為null的話,拋出NoSuchElementException異常
實例如下:
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); }
通過源碼可以知道:如果Optional實例有值則為其調用consumer,否則不做處理
實例如下:
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; }
通過注釋可以知道:如果value不為null的話直接返回value,否則返回傳入的other值。
實例如下:
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(); }
通過注釋可以知道:orElseGet與orElse方法類似,區別在于得到的默認值。orElse方法將傳入的字符串作為默認值,orElseGet方法可以接受Supplier接口的實現用來生成默認值
實例如下:
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} * * @param <X> Type 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 <X extends Throwable> T orElseThrow(Supplier<? extends X> exceptionSupplier) throws X { if (value != null) { return value; } else { throw exceptionSupplier.get(); } }
通過注釋可以得知:如果有值則將其返回,否則拋出supplier接口創建的異常。
實例如下:
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<FileInputStream>}: * * <pre>{@code * Optional<FileInputStream> fis = * names.stream().filter(name -> !isProcessedYet(name)) * .findFirst() * .map(name -> new FileInputStream(name)); * }</pre> * * Here, {@code findFirst} returns an {@code Optional<String>}, and then * {@code map} returns an {@code Optional<FileInputStream>} for the desired * file if one exists. * * @param <U> 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<U> Optional<U> map(Function<? super T, ? extends U> mapper) { Objects.requireNonNull(mapper); if (!isPresent()) return empty(); else { return Optional.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
源碼: /** * 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 <U> 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<U> Optional<U> flatMap(Function<? super T, Optional<U>> mapper) { Objects.requireNonNull(mapper); if (!isPresent()) return empty(); else { return Objects.requireNonNull(mapper.apply(value)); } }
通過注釋可以得知:如果有值,為其執行mapping函數返回Optional類型返回值,否則返回空Optional。
實例如下:
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 Optional<T> filter(Predicate<? super T> predicate) { Objects.requireNonNull(predicate); if (!isPresent()) return this; else return predicate.test(value) ? this : empty(); }
通過代碼可以得知:如果有值并且滿足斷言條件返回包含該值的Optional,否則返回空Optional。
實例如下:
List<String> names = Arrays.asList("javaHuang","tony"); for(String s:names) { Optional<String> nameLenLessThan7 = Optional.of(s).filter((value) -> "tony".equals(value)); System.out.println(nameLenLessThan7.orElse("The name is javaHuang")); }
感謝各位的閱讀,以上就是“java8的新特性有哪些”的內容了,經過本文的學習后,相信大家對java8的新特性有哪些這一問題有了更深刻的體會,具體使用情況還需要大家實踐驗證。這里是億速云,小編將為大家推送更多相關知識點的文章,歡迎關注!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。