gpt4 book ai didi

Java8 嵌套流用 setter 回写

转载 作者:行者123 更新时间:2023-11-30 06:14:07 24 4
gpt4 key购买 nike

我试图遍历两个列表,过滤嵌套列表并将结果写回具有 java8 功能的主对象。

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

所以现在 location 中的子列表没有改变,这是很明显,因为 stream 和 collect 确实创建了一个新列表,它不会写回位置对象。所以我的问题是,是否有办法调用 setSubList(...) 方法位置对象并将新列表写入其中。

谢谢

最佳答案

我会使用 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)));

关于Java8 嵌套流用 setter 回写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30875951/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com