How to 'walk' multiple directories, with multiple file extensions, in java?

Cruxial :

Here is my actual code, which works perfectly :
String sHomeDir is my only folder where to start the scan
String sExt is the only extension to search for

try (Stream<Path> walk = Files.walk(Paths.get(sHomeDir)))
{
    List<String> result = walk.map(x -> x.toString())
        .filter(f -> f.endsWith(sExt)).collect(Collectors.toList());
    ...
} catch (IOException e) {
   e.printStackTrace();
}

Is it possible to rewrite that, in order to use :
- Multiple folders to scan (with subtree)
- Multiple file extensions to search for

Thank you !

Mureinik :

To handle multiple directories, you can stream them and flatmap them to a single stream of Paths. To handle multiple extensions, you just need to check the file against them all:

public static List<String> multiWalk
    (Collection<String> directories, Collection<String> extensions) {

    return directories.stream()
                      .flatMap(d -> {
                          try {
                              return Files.walk(Paths.get(d));
                          } catch (IOException e) {
                              return Stream.empty();
                          }
                      })
                      .map(Object::toString)
                      .filter(f -> extensions.stream().anyMatch(f::endsWith))
                      .collect(Collectors.toList());
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=296444&siteId=1