Java execution method for all objects in a list

I have this 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 tell all listeners that A, B, C occurred through Listener.onA() , Listener.onB() , Listener.onC() ?

Do I need to copy-paste iteration over all listeners at least three times?

In C ++, I would create a function like this:

 void Notify(const std::function<void(Listener *listener)> &command) { for(auto &listener : listeners) { command(listener); } } 

And skip lambda for each of the 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?

+5
source share
2 answers

In Java 8 there are:

 listeners.forEach(listener -> listener.onA()); 

or

 listeners.forEach(Listener::onA); 

Note that there are many other functional programming-style operations that can be performed using lambda functions, but for most of them, you will first need to create a stream from your collection by calling .stream() on it. forEach() , as I learned from the comments, is an exception to this.

+6
source

If your java version does not allow Lambdas to do:

 List<Listener> l = ... for (Listener myListeners : listenersList) { myListeners.onA(); myListeners.onB(); myListeners.onC(); } 
+1
source

Source: https://habr.com/ru/post/1247548/


All Articles