【发布时间】:2020-12-21 17:18:22
【问题描述】:
基于用户@eitan https://stackoverflow.com/a/37334159/11214643 给出的响应,关于如何使用lambda 执行自动转换的可读切换案例,但也基于用户@Al-Mothafar 的问题,我想这是一个有效的观点,尝试中断循环而不是仅仅失败执行循环内的所有消费者,有没有办法遍历所有消费者并在其中一个接受()子句时中断迭代?
我在想这样的事情,这样做有什么好处吗?
public static <T> void switchType(Object o, @NotNull Consumer... a) {
AtomicBoolean accepted = new AtomicBoolean(false);
for (Consumer consumer : a) {
//I'm not sure if the andThen() method will only execute if the ifPresent(c) clause of the original consumer (code down below) executes.
//If the andThen() method always executes regardless of whether the execution of the first accept() materializes or not, then this wont work because it will always be executed.
consumer.andThen(
object -> {
accepted.set(true);
}
);
if (accepted.get()) break;
}
}
与简单地执行失败所有消费者相比,这种分支的性能最差吗?
@eitan 回答中的消费者方法:
public static <T> Consumer caze(Class<T> cls, Consumer<T> c) {
return obj -> Optional.of(obj).filter(cls::isInstance).map(cls::cast).ifPresent(c);
}
【问题讨论】:
-
andThen返回一个新的消费者,必须使用它来代替原始消费者才能产生任何影响。您忽略了andThen方法返回的新消费者。您的操作将永远不会被执行
标签: java performance loops consumer branch-prediction