I have the following for loop:
List<Map> mapList = new ArrayList<>();
for (Resource resource : getResources()) {
for (Method method : resource.getMethods()) {
mapList.add(getMap(resource,method));
}
}
return mapList;
How could I refactor this nested loop into a Java 8 stream?
Eran
You can use flatMap
to obtain all the Map
s for all Method
s of all Resource
s :
List<Map> mapList =
getResources().stream()
.flatMap(r->r.getMethods().stream().map(m->getMap(r,m)))
.collect(Collectors.toList());
来源:https://stackoverflow.com/questions/34589980/refactoring-nested-for-loop-into-java-8-stream