如何优雅的判空
如何優雅的判空
?
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);總結