简体   繁体   English

Java 8 可选择在分层对象中进行空检查

[英]Java 8 Optional to do null check in hierarchical objects

Using Optional to Null Check While Object Cloning different type of object.在对象克隆不同类型的对象时使用 Optional 进行空检查。

class A{ C cObj; List<B> bList;}

class B{ C cObj; List<C> cList;}

class C { String label; String value;}

class D{ String name; String age; String addressCode;}

Mapping A -> D映射 A -> D

d.setAddessCode(A.getBlist().get(0).getcList().get(0).getValue());

How can check null using java 8 optional如何使用 java 8 可选检查 null

A.getBlist().get(0).getcList().get(0).getValue()

I tried我试过了

d.setAddessCode(Optional.ofNullable(A).map(A::getBList).map(Stream::of).orElseGet(Stream::empty).findFirst().map(B::getCList).map(Stream::of).orElseGet(Stream::empty).findFirst().map(C::getValue).orElse(null)));

How can i check null in List and value together.如何一起检查 List 和 value 中的 null。

There is no need to use Streams.无需使用 Streams。 Here is code with both null and empty checks:这是带有空检查和空检查的代码:

d.setAddressCode(Optional.ofNullable(a)
                         .map(A::getbList)
                         .filter(bList -> ! bList.isEmpty())
                         .map(bList -> bList.get(0))
                         .map(B::getcList)
                         .filter(cList -> ! cList.isEmpty())
                         .map(cList -> cList.get(0))
                         .map(C::getValue)
                         .orElse(null));

That can be simplified with a little helper method:这可以通过一个小助手方法来简化:

public class MyUtils {
    public static <E> E getFirst(List<E> list) {
        return (list == null || list.isEmpty() ? null : list.get(0));
    }
}
d.setAddressCode(Optional.ofNullable(a)
                         .map(A::getbList)
                         .map(MyUtils::getFirst)
                         .map(B::getcList)
                         .map(MyUtils::getFirst)
                         .map(C::getValue)
                         .orElse(null));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM