When using Stream.forEach(), I was thinking if it is not possible to add a pre-action and post-action to be executed when the stream is not empty. For example, when printing a List, one could prepend something or write something else when the stream is empty.
Now I came up with something like
private static <T> void forEach(Stream<T> stream, Consumer<? super T> action,
Runnable preAction, Runnable postAction, Runnable ifEmpty) {
AtomicBoolean hasElements = new AtomicBoolean(false);
Consumer<T> preActionConsumer = x -> {
if (hasElements.compareAndSet(false, true)) {
preAction.run();
}
};
stream.forEach(preActionConsumer.andThen(action));
if (hasElements.get()) {
postAction.run();
} else {
ifEmpty.run();
}
}
For sequential streams, this should work, should it not? Is this method correct, is it as "good idea" have such a method or are there any caveats?
This does not work for parallel streams, since the preAction might be slower than another thread executing the action, but implementing it correctly without resorting to synchronized or other concurrency utils which defeat the purpose of parallel streams will probably be not easy...
edit: adding use-case. Reading searching integers from a file using a regex and writing them to another file. Using this approach, I don't have to create a String in memory and after that write it to some file. (Obviously, for my real task, I am using more complicated regexes.)
public static void main(String[] args) throws IOException {
Stream<String> lines = Files.lines(Paths.get("foo.txt"));
Pattern findInts = Pattern.compile("(\\d+)");
Path barFile = Paths.get("bar.txt");
try (BufferedWriter writer = Files.newBufferedWriter(barFile , StandardOpenOption.CREATE_NEW)) {
lines.flatMap(x -> findInts.matcher(x).results())
.forEach(x-> convertCheckedIOException(() -> {
writer.write(x.group(1));
writer.newLine();
})
);
}
}
public static void convertCheckedIOException(Run r) {
try {
r.run();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
interface Run {
void run() throws IOException;
}