有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java Java8嵌套流使用setter写回

我试图循环两个列表,过滤嵌套列表,并使用java8特性将结果写回主对象

locations.forEach(location -> location.getSubList().stream()
            .filter(this::correctTestDataValue)
            .collect(Collectors.toList()));

因此,到目前为止,位置内部的子列表没有改变,这是 很明显,因为stream和collect确实创建了一个新列表 不会回写到位置对象中。 所以我的问题是,如果有办法调用setpublist(…)方法 并将新列表写入其中

Thx


共 (1) 个答案

  1. # 1 楼答案

    我将使用for循环:

    for (Location location : locations) {
      List<?> newList = location.getSubList().stream()
                                             .filter(this::correctTestDataValue)
                                             .collect(Collectors.toList());
      location.setSubList(newList);
    }
    

    或者,如果可以就地移除:

    for (Location location : locations) {
      location.getSubList().removeIf(x -> !correctTestDataValue(x));
    }
    

    它可以作为流工作:

    locations.stream()
        .map(Location::getSublist)
        .forEach(list -> list.removeIf(x -> !correctTestDataValue(x)));