Else clause in lambda expression

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 is .forEach(Start::modify); executes a static method, mutable from the same class as the lambda expression. Is there any way to add something like the else clause when the pdf file is not found?

+5
source share
3 answers

You can collect the result after the filter operation into an instance of the list, and then check the size before it works.

 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 can do something like this:

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

Or you could just do the obvious thing that collects the stream first.

 List<File> files = Files.walk(rootDir) .filter(matcher::matches) .collect(toList()); if (files.isEmpty()) doSomethingForEmpty(); else files.forEach(Start::modify); 
+6
source

If the API gives you Stream , but Stream not what you need, you can always convert it to Iterable and use a simple loop:

 boolean fileModified = false; for (Path path : (Iterable<Path>) Files.walk(rootDir)::iterator) { if (matcher.matches(path)) { Start.modify(path); fileModified = true; } } if (!fileModified) { // do something } 

Iterates files only once and does not require the formation of an intermediate collection.

+1
source

Source: https://habr.com/ru/post/1276068/


All Articles