如何优雅的判空
如何優(yōu)雅的判空
?
Scene1 判空并操作:
先看一個(gè)例子:
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);} }?
在上面的例子中,對(duì)father的操作以及取出father對(duì)象的name后的輸出都需要先判空,在我們?nèi)粘5臉I(yè)務(wù)中經(jīng)常也會(huì)有類似的業(yè)務(wù)場(chǎng)景,那么能寫的稍微優(yōu)雅一點(diǎn)嗎?當(dāng)然可以。
?
上述代碼可以改寫成:
?
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);?
對(duì)于上述方法的使用方法:
// 如果不關(guān)心方法返回的結(jié)果,只希望在對(duì)象不為空的情況下執(zhí)行 Optional.ofNullable(father).ifPresent(Father::callName);// 關(guān)心返回值的時(shí)候,可以使用map方法和flatMap方法// flatMap 可以自定義 方法返回值為null時(shí)Optional的值,而map會(huì)在返回值為null時(shí)取 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判空并操作:
同理,對(duì)于List的操作也會(huì)有類似的判空,在每次使用stream操作之前,都需要先進(jìn)行判空。
List<Father> fatherList = getRandomFatherList();if (CollectionUtils.isNotEmpty(fatherList)) {fatherList.forEach(Father::callName);}?
可以改寫成:
CollectionUtils.emptyIfNull(fatherList).forEach(Father::callName);?
CollectionUtils 為 org.apache.commons.collections4.CollectionUtils
在每次進(jìn)行集合操作之前可以將null 轉(zhuǎn)化為一個(gè)空的Collection。防止空指針。
?
Scene3 集合插空值:
在某些情況下,還有需要放置給list中可能會(huì)插入null的情況,例如:
Father f = getRandomFather(); if (f !=null ){fatherList.add(f); }?
可以改寫為:
CollectionUtils.addIgnoreNull(fatherList,f);總結(jié)
- 上一篇: 一个网站的演进之路
- 下一篇: Spring中类路径下文件读取方式