【问题标题】:Inside java stream the map function does not recognize my local variable在 java 流中,map 函数无法识别我的局部变量
【发布时间】:2018-09-20 08:46:16
【问题描述】:

我正在尝试使用 java 流在 jsonNode 流中进行搜索。有一次,我收到了一个 ArrayNode,并在我的类中使用一个简单的私有方法将其转换为 JsonNodes 列表;但是,当我想使用映射函数来映射我的节点时,我意识到局部变量(节点;在第一个映射中)为空。考虑到我是 Java 8 的新手,我不明白为什么以及如何解决这个问题。我在这里发布我的代码:

List<JsonNode> msgs = arrayNodeToListNode((ArrayNode) kmsResponse.at(kmsResponsePath));
        msgs.stream().forEach(t -> {
            List<JsonNode> jsonNodes = arrayNodeToListNode((ArrayNode) t.get("coverageList"));
            List<JsonNode> collect = jsonNodes.stream()
                    .map(node -> node.get("/coverage/coverageTypeLevel"))
                    .filter(node -> formule.equals(node.get("aggReference").textValue()))
                    .map(node -> t.get("premiumSplittedList"))
                    .map(node -> node.get("value")).collect(Collectors.toList());
            String value = collect.toString();
            response.append(collect);
        });

【问题讨论】:

  • 愿意提供一些细节吗?你得到一个编译错误?

标签: java-8 java-stream jsonnode


【解决方案1】:

如果您的nodenull,这与流或Java 8 无关,只是您的arrayNodeToListNode 操作在列表中返回了一些null json 节点。

错误(如果有)在arrayNodeToListNode 方法中。如果该方法返回包含一些null 元素的列表是有效的,那么您可以在使用Stream.map 之前完美地过滤掉nulls,使用Stream.filter(Objects::nonNull)

List<JsonNode> jsonNodes = arrayNodeToListNode((ArrayNode) t.get("coverageList"));
List<JsonNode> collect = jsonNodes.stream()
    .filter(Objects::nonNull)
    .map(node -> node.get("/coverage/coverageTypeLevel"))
    ...

【讨论】:

    【解决方案2】:

    事实上我已经解决了我的问题;我在 intelliJ 中调试我的应用程序时遇到了这样一个事实,即在 IntelliJ 的调试器中节点为空。原因很简单,因为我不知道要在调试器模式下添加断点,我需要选择\lambda而不是“line”。

    这就是问题所在。其实一切都很好,没有空指针问题。事实上,我有另一个过滤器问题,一旦我发现了 intelliJ 的调试器如何用于 lambda 表达式,我就解决了我的问题。最后,我得到了运行良好的代码:

    StringBuilder response = new StringBuilder();
        List<JsonNode> msgs = arrayNodeToListNode((ArrayNode) kmsResponse.at(kmsResponsePath));
        List<JsonNode> collect1 = msgs.stream().filter(node -> {
                    List<JsonNode> collect = arrayNodeToListNode((ArrayNode) node.get("coverageList")).stream()
                            .map(entry -> entry.at("/coverage/coverageTypeLevel"))
                            .filter(enttry -> formule.equals(enttry.get("aggReference").textValue())).collect(Collectors.toList());
                    return collect.size() > 0;
                }
    
        ).collect(Collectors.toList());
    response.append(collect1);
    

    谢谢。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-03-11
      • 1970-01-01
      • 2021-01-06
      • 1970-01-01
      • 2018-11-12
      • 2015-12-08
      • 1970-01-01
      相关资源
      最近更新 更多