crm*_*ham 6 java java-8 java-stream
给定以下 Java 8 流:
scheduleService.list().stream()
.filter(Schedule::getEnabled)
.filter(this::runnable)
.flatMap(s -> s.getJobs().stream())
// .doSomethingArbitrary(System.out.println("A single message. The total number of
// elements in the stream after filtering is " + this::count))
.forEach(this::invoke);
Run Code Online (Sandbox Code Playgroud)
将过滤应用于流并应用第一个终端操作后,如果流为空,我想记录一条调试消息,或者如果不是,则对流invoke中的每个元素调用该方法。这可能吗?
您可以将您的方法包装Stream到如下所示的自定义方法中
Stream<???> stream = scheduleService.list().stream()
.filter(Schedule::getEnabled)
.filter(this::runnable)
.flatMap(s -> s.getJobs().stream());
forEachOrElse(stream, this::invoke, () -> System.out.println("The stream was empty"));
Run Code Online (Sandbox Code Playgroud)
与forEachOrElse存在
public <T> void forEachOrElse(Stream<T> inStream, Consumer<T> consumer, Runnable orElse) {
AtomicBoolean wasEmpty = new AtomicBoolean(true);
inStream.forEach(e -> {
wasEmpty.set(false);
consumer.accept(e);
});
if (wasEmpty.get())
orElse.run();
}
Run Code Online (Sandbox Code Playgroud)
我现在无法测试它,但它应该发挥其魔力