如何優雅的判空
Scene1 判空並操作:
先看一個例子:
package *; import lombok.Data; import java.util.Random; public class Test { private static Father getSomeoneFather() { return Math.random() > 0.5 ? new Father() : null; } public static void main(String[] args) { Father father = getSomeoneFather(); // 判空,不爲空可以操作 if (father !=null) { father.callName(); String name = father.getName(); // 判空, 不爲空則打印 if (name !=null) { System.out.println(name); } } } } @Data class Father { private String name; public void callName() { System.out.println("my name is " + name); } }
在上面的例子中,對father的操作以及取出father對象的name後的輸出都需要先判空,在我們日常的業務中經常也會有類似的業務場景,那麼能寫的稍微優雅一點嗎?當然可以。
上述代碼可以改寫成:
Father father = new Father(); Optional.ofNullable(father).ifPresent(Father::callName); Optional.ofNullable(father).flatMap(f -> f.getName()== null ? null : Optional.of(f.getName())).ifPresent(System.out::println);
對於上述方法的使用方法:
// 如果不關心方法返回的結果,只希望在對象不爲空的情況下執行 Optional.ofNullable(father).ifPresent(Father::callName); // 關心返回值的時候,可以使用map方法和flatMap方法 // flatMap 可以自定義 方法返回值爲null時Optional的值,而map會在返回值爲null時取 Optional.empty(); Optional.ofNullable(father).flatMap(f -> f.getName()== null ? null : Optional.of(f.getName())).ifPresent(System.out::println); Optional<String> fName2 = Optional.ofNullable(father).map(Father::getName);
Scene2 list判空並操作:
同理,對於List的操作也會有類似的判空,在每次使用stream操作之前,都需要先進行判空。
List<Father> fatherList = getRandomFatherList(); if (CollectionUtils.isNotEmpty(fatherList)) { fatherList.forEach(Father::callName); }
可以改寫成:
CollectionUtils.emptyIfNull(fatherList).forEach(Father::callName);
CollectionUtils 爲 org.apache.commons.collections4.CollectionUtils
在每次進行集合操作之前可以將null 轉化爲一個空的Collection。防止空指針。
Scene3 集合插空值:
在某些情況下,還有需要放置給list中可能會插入null的情況,例如:
Father f = getRandomFather(); if (f !=null ){ fatherList.add(f); }
可以改寫爲:
CollectionUtils.addIgnoreNull(fatherList,f);