Replacing repetitive get statement with Java 8 Optional

前端 未结 2 349
南笙
南笙 2021-01-18 19:30

I have a use case, where I have nested classes and an object of the top class. I want to get a value which is at the Nth level. I\'m using getters repetitively to achieve th

2条回答
  •  情话喂你
    2021-01-18 19:50

    Use Optional with a series of map() calls for a nice one-liner:

    String getAValue(D d) {
       return Optional.ofNullable(d)
           .map(D::getC).map(C::getB).map(B::getA).map(A::getA1).orElse(null);
    }
    

    If anything is null along the chain, including d itself, the orElse() will execute.

提交回复
热议问题