Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to traverse a nested list in an optional?

I have an object node which has a getNodes() method that returns a list, and I want to traverse this list only if node is not null.

I tried to do the following where I thought I could map the stream of the list and traverse it, but what happens is that it tries to perform the filter on the Stream Object and not on the contents of the list.

public void updateNode(Node node) {
    List<Node> nodes = Optional.ofNullable(node)
                   .map(node -> Stream.of(node.getNodes))
                   .filter().......orElse()

    // operation on filtered nodes.
    ....

}
like image 306
Fernando Ania Avatar asked Nov 25 '25 05:11

Fernando Ania


1 Answers

You're probably better off just using a simple if not null statement than introducing an optional. It makes the code more readable and reduces overhead.

if (node != null) {
    node.getNodes().stream.filter(...
}

Also, you are returning from a void method.

like image 89
AntPraxis Avatar answered Nov 27 '25 20:11

AntPraxis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!