解決java.util.NoSuchElementException: No value present 異常問題

問題描述

在這裏插入圖片描述

代碼如下

 Comparator<User> userComparator = Comparator.comparing(User::getCreateT);
 String recentUserServer = users.stream().max(userComparator).get().getServer();

源碼分析

也就是當get的調用主體查詢不到、爲空時,就會報 No value present 異常問題

/**
 * 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;
}

也就是說當查不到值的時候,Optional會統一處理爲拋異常,所以每次取之前都要判斷有沒有數據,後來發現了這個判斷空指針的方法

/**
 * 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;
}

解決代碼

因此代碼做如下的判空

Comparator<User> userComparator = Comparator.comparing(User::getCreateT);
String recentUserServer = null;
Optional<User> optional = users.stream().max(userComparator);
if(optional != null && optional.isPresent()) {
    recentUserServer = optional.get().getServer();
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章