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?
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:
public static <T> Consumer caze(Class<T> cls, Consumer<T> c) {
return obj -> Optional.of(obj).filter(cls::isInstance).map(cls::cast).ifPresent(c);
}