Reputation: 710
I´m trying to loop over two lists, filter the nested list and write the result back into the main object with java8 features.
locations.forEach(location -> location.getSubList().stream()
.filter(this::correctTestDataValue)
.collect(Collectors.toList()));
So by now the sublist inside location doesnt change, which is obvious because stream and collect do create a new list, which is not written back into the location object. So my question is, if there is a way to call the setSubList(...) method of the location object and writing the new list into it.
Thx
Upvotes: 2
Views: 1473
Reputation: 328608
I would use a for loop:
for (Location location : locations) {
List<?> newList = location.getSubList().stream()
.filter(this::correctTestDataValue)
.collect(Collectors.toList());
location.setSubList(newList);
}
Or if you can remove in place:
for (Location location : locations) {
location.getSubList().removeIf(x -> !correctTestDataValue(x));
}
Which can work as a stream:
locations.stream()
.map(Location::getSublist)
.forEach(list -> list.removeIf(x -> !correctTestDataValue(x)));
Upvotes: 5