简体   繁体   中英

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.
    ....

}

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.

In the worst of the implementation choices, to the correct answer here to place a null check one has the following alternates available:

Optional.ofNullable(node)
        .map(Node::getNodes)
        .orElse(Collections.emptyList())
        .stream() // Stream of nodes
        .filter(...)

or with Java-9 +

Stream.ofNullable(node)
        .flatMap(nd -> nd.getNodes().stream())
        .filter(...)

In your code:

 Optional.ofNullable(node).map(node -> Stream.of(node.getNodes))

This creates a stream of a single item: the list of nodes itself.

Stream.of(node.getNodes))

Instead of that, to get a stream of the nodes, where you can then filter the node, use:

node.getNodes().stream().filter(... 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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