Else clause in lambda expression

menteith :

I use the following lambda expression to iterate over PDF files.

public static void run(String arg) {

        Path rootDir = Paths.get(arg);
        PathMatcher matcher = FileSystems.getDefault().getPathMatcher("glob:**.pdf");
        Files.walk(rootDir)
                .filter(matcher::matches)
                .forEach(Start::modify);
    }

    private static void modify(Path p) {
        System.out.println(p.toString());
    }

This part .forEach(Start::modify); executes the static method modify from the same class where the lambda expression is located. Is there a possibility to add something like else clause when no PDF file is found?

Ousmane D. :

You could collect the result after the filter operation into a list instance and then check the size before operating on it.

List<Path> resultSet = Files.walk(rootDir)
                            .filter(matcher::matches)
                            .collect(Collectors.toList());
if(resultSet.size() > 0){
    resultSet.forEach(Start::modify);
}else {
    // do something else   
}

Alternatively, you could do something like this:

if(Files.walk(rootDir).anyMatch(matcher::matches)) {
         Files.walk(rootDir)
              .filter(matcher::matches)
              .forEach(Start::modify);
}else {
        // do something else    
}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=469319&siteId=1