, , , Stream.onClose. , :
class CloseHandler implements Runnable {
List<Runnable> children = new ArrayList<>();
void add(Runnable ch) { children.add(ch); }
@Override
public void run() { children.forEach(Runnable::run); }
}
:
CloseHandler closeAll = new CloseHandler();
try (Stream<Something> stream = list.stream().onClose(closeAll)) {
stream.collect(Collectors.groupingBy(
this::extractFileName,
toFile(closeAll)));
}
try-with-resources, , . , close closeAll Stream.onClose.
, // Closeable ( , closeAll):
static Collector<Something, ?, Void> toFile(CloseHandler closeAll) {
class Acc {
SomeResource resource;
Acc() {
try {
resource = new SomeResource(...);
closeAll.add(this::close);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
void add(Something elem) {
try {
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
Acc merge(Acc another) {
}
private void close() {
try {
if (resource != null) resource.close();
} catch (IOException ignored) {
}
}
}
return Collector.of(Acc::new, Acc::add, Acc::merge, a -> null);
}
, ( Acc) add , merge Acc , ( , ).
Collector.of Acc, , null, - , Collectors.groupingBy.
, close, .
try-with-resources, CloseHandler.run , , , , , Acc .