问题描述
基于用户@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);
}
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)