Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Else clause in lambda expression

Tags:

java

lambda

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?

like image 980
menteith Avatar asked Mar 25 '18 17:03

menteith


1 Answers

Or you could just do the obvious thing, which is collect the stream first.

List<File> files = Files.walk(rootDir)
            .filter(matcher::matches)
            .collect(toList());

if (files.isEmpty())
    doSomethingForEmpty();
else
    files.forEach(Start::modify);
like image 67
Brian Goetz Avatar answered Sep 20 '22 03:09

Brian Goetz