[英]Get an element from a list in a Nested optional check
我有以下嵌套的空檢查。 試圖通過Optional
使其可讀,但是如何映射第一個元素?
卡在下面,不確定如何映射這條線
vo.getSomething().getAnother().get(0)
我被困在三號線
Optional.of(vo.getSomething)
.map(Something::getAnother)
.map(List<Another>::get(0)) // will not work
這是一個有效的空檢查。 我正在嘗試使用Optional清理它。
if(vo.getSomething() != null){
if(vo.getSomething().getAnother() != null){
if(vo.getSomething().getAnother().get(0) != null){
if(vo.getSomething().getAnother().get(0).getInner() != null){
if(vo.getSomething().getAnother().get(0).getInner() != null){
if(vo.getSomething().getAnother().get(0).getInner().get(0) != null){
return vo.getSomething().getAnother().get(0).getInner().get(0).getProductName();
}
}
}
}
}
}
Lambda表達式
.map(list -> list.get(0))
應該管用。 有些想法不能通過方法引用來表達。
List<Another>::get(0)
不是有效的方法引用,而List<Another>::get
可以。
BiFunction<List<String>, Integer, String> function = List::get;
該表達式的問題在於它具有常數0
,您需要顯式傳遞它。
但是,您可以編寫一個靜態方法
class ListFunctions {
public static <T> T getFirst(List<? extends T> list) {
return list.get(0);
}
}
並通過方法參考進行引用
.map(ListFunctions::getFirst)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.