I've got such an interface:
public interface Listener {
void onA();
void onB();
void onC();
}
And there is a list of listeners/observers:
List<Listener> listeners = new ArrayList<Listener>();
How can I easily inform all listeners, that A, B, C occurred via Listener.onA()
, Listener.onB()
, Listener.onC()
?
Do I have to copy-paste iteration over all listeners at least three times?
In C++ I would create such a function:
void Notify(const std::function<void(Listener *listener)> &command) {
for(auto &listener : listeners) {
command(listener);
}
}
And pass lambda for each of methods:
Notify([](Listener *listener) {listener->onA();});
or
Notify([](Listener *listener) {listener->onB();});
or
Notify([](Listener *listener) {listener->onC();});
Is there a similar approach in Java?
In Java 8, there is:
listeners.forEach(listener -> listener.onA());
or:
listeners.forEach(Listener::onA);
Note that there's a host of other functional-programming-style operations that can be performed with lambda functions, but most of them will require that you first create a stream from your collection by calling .stream()
on it. forEach()
, as I learned from the comments, is an exception to this.
If your java version is not allowing a Lambdas then do:
List<Listener> l = ...
for (Listener myListeners : listenersList) {
myListeners.onA();
myListeners.onB();
myListeners.onC();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With