简体   繁体   English

如何跳出消费者循环

[英]How to break out of a loop of Consumers

Based on the response given by user @eitan https://stackoverflow.com/a/37334159/11214643 , on how to perform readable switch cases for auto casting using lambdas, but also based on user @Al-Mothafar 's question, which I guess is a valid point, to try to interrupt the loop instead of just fail-executing all consumers inside the loop, is there a way to iterate throught all Consumers and break iteration if one of them accepts() the clause?基于用户@eitan https://stackoverflow.com/a/37334159/11214643给出的响应,关于如何使用 lambdas 执行自动转换的可读切换案例,但也基于用户 @Al-Mothafar 的问题,其中我想这是一个有效的观点,尝试中断循环而不是仅仅执行循环内的所有消费者失败,有没有办法遍历所有消费者并在其中一个接受()子句时中断迭代?

I was thinking something like this, is there any advantage on doing this?我在想这样的事情,这样做有什么好处吗?

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;
     }
  }

Is this branching worst for performance than simply fail-executing all consumers?与简单地执行所有消费者失败相比,这种分支对性能的影响是否最差?

The consumer method from @eitan 's answer: @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);
} 

I found a way to break the loop by creating an interface that gave a boolean value, that after performing the Optional validation and Consumer execution, returns whether the value .isPresent(), or not.我找到了一种通过创建一个提供布尔值的接口来打破循环的方法,在执行可选验证和消费者执行后,返回值是否为 .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();
        };
    }
}

This makes possible for the loop to check if it should or shouldn't break.这使得循环可以检查它是否应该或不应该中断。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM