简体   繁体   English

如何遍历可选中的嵌套列表?

[英]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 .我有一个对象node ,它有一个返回列表的getNodes()方法,并且我只想在node不为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.我尝试执行以下操作,我认为我可以映射列表的流并遍历它,但发生的情况是它尝试对 Stream 对象而不是列表的内容执行过滤器。

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.与引入可选项相比,您最好使用简单的 if not null 语句。 It makes the code more readable and reduces overhead.它使代码更具可读性并减少了开销。

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

Also, you are returning from a void method.此外,您正在从 void 方法返回。

In the worst of the implementation choices, to the correct answer here to place a null check one has the following alternates available:在最糟糕的实现选择中,对于此处放置null检查的正确答案,有以下替代方案可用:

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

or with Java-9 +或使用 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(... 

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

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