将嵌套for循环重构为Java 8流

S-K*_*-K' 1 java java-8 java-stream

我有以下for循环:

    List<Map> mapList = new ArrayList<>();
    for (Resource resource : getResources()) {
        for (Method method : resource.getMethods()) {
            mapList.add(getMap(resource,method));
        }
    }
    return mapList;
Run Code Online (Sandbox Code Playgroud)

我怎么能将这个嵌套循环重构为Java 8流?

Era*_*ran 11

您可以使用flatMap获取Map所有Methods的所有Resources:

List<Map> mapList = 
    getResources().stream()
                  .flatMap(r->r.getMethods().stream().map(m->getMap(r,m)))
                  .collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)