首页 > 解决方案 > 我正在尝试通过使用 java 8 流遍历嵌入列表来返回数据

问题描述

我正在努力返回仅包含 item.baz.fooz == 'snafu' 的项目。我已经匿名化了下面的代码和源代码。您的帮助将不胜感激。我的数据来源:

{
  "data": {
    "searches": [
      {
        "apples": [
          {
            "pears": [
              {
                "sets": [
                  {
                    "items": [
                      {
                        "baz": {
                          "fooz": {
                            "unit": "snafu"
                          }
                        }
                      }
                    ]
                  }
                ]
              }
            ]
          }
        ]
      }
    ]
  }
}

我失败的代码:

List<Item> items =
    response.data.searches.stream()
    .flatMap(
        search -> search.apples.forEach(
           apple -> apple.pears.forEach(
               pear -> pear.sets.forEach(
                   set -> set.items.stream()
                      .filter(item -> item.baz.fooz.unit.equals("snafu"))
                      .collect(Collectors.toList())))));

失败是(除其他外):

Incompatible type. Required List<Foo> but 'flatmap' was inferred to Stream<R>: no instances of type variable R List<Foo>

标签: javalambdajava-8java-stream

解决方案


不要使用forEach,你需要多个flatMaps:

List<Item> snoozles =
    response.data
            .searches
            .stream() // Stream<Search>
            .flatMap(search -> search.apples.stream()) // Stream<Apple>
            .flatMap(apple -> apple.pears.stream()) // Stream<Pear>
            .flatMap(pear -> pear.sets.stream()) // Stream<Set>
            .flatMap(set -> set.items.stream() 
                               .filter(item -> item.baz.fooz.unit.equals("snafu"))) // Stream<Item>
            .collect(Collectors.toList()); // List<Item>

或者(正如霍尔格建议的那样):

List<Item> snoozles =
    response.data
            .searches
            .stream() // Stream<Search>
            .flatMap(search -> search.apples.stream()) // Stream<Apple>
            .flatMap(apple -> apple.pears.stream()) // Stream<Pear>
            .flatMap(pear -> pear.sets.stream()) // Stream<Set>
            .flatMap(set -> set.items.stream()) // Stream<Item>
            .filter(item -> item.baz.fooz.unit.equals("snafu")) // Stream<Item>
            .collect(Collectors.toList()); // List<Item>

推荐阅读