【问题标题】:How to break out of a loop of Consumers如何打破消费者循环
【发布时间】: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


【解决方案1】:

我找到了一种打破循环的方法,方法是创建一个提供布尔值的接口,在执行可选验证和消费者执行后,返回值是否为 .isPresent()。

public class Switch {
    public static <T> void caze(Object o, Caze... a) {
        for (Caze consumer : a) {
            if (consumer.isPresent(o)) break;
        }
    }

    @FunctionalInterface
    public interface Caze {
        boolean isPresent(Object obj);
    }

    public static <T> Caze type(Class<T> cls, Consumer<T> c) {
        return obj -> {
            Optional<T> o = Optional.of(obj).filter(cls::isInstance).map(cls::cast);
            o.ifPresent(c);
            return o.isPresent();
        };
    }
}

这使得循环可以检查它是否应该中断。

【讨论】:

    猜你喜欢
    • 2018-08-26
    • 2019-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多