Adam Siemion Adam Siemion - 18 days ago 9
Java Question

Perform an action for each element of a stream and for any element

I would like to be able to do this:

Arrays.stream(args)
.map(arg -> new File(arg))
.filter(file -> !file.isFile())
.forEach(
file -> System.out.println(String.format("File %s does not exist", file))
).forAny(() -> System.exit(1));


but since
forEach
returns
void
I have the following code:

Stream<File> notExistingFiles = Arrays.stream(args)
.map(arg -> new File(arg))
.filter(file -> !file.isFile());
notExistingFiles.forEach(
file -> System.out.println(String.format("File %s does not exist", file))
);
notExistingFiles.findAny().ifPresent(a -> System.exit(1));


Any suggestions how this can be improved?

Answer

Maybe:

Arrays.stream(args)
    .map(arg -> new File(arg))
    .filter(file -> !file.isFile())
    .peek(file -> System.out.println(String.format("File %s does not exist", file)))
    .findAny()
    .ifPresent(() -> System.exit(1));