Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java execute method on all objects in a List

Tags:

java

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?

like image 745
Dejwi Avatar asked Apr 20 '16 19:04

Dejwi


2 Answers

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.

like image 81
Aasmund Eldhuset Avatar answered Oct 02 '22 20:10

Aasmund Eldhuset


If your java version is not allowing a Lambdas then do:

List<Listener> l = ...
for (Listener myListeners : listenersList) {
    myListeners.onA();
    myListeners.onB();
    myListeners.onC();
}
like image 40
ΦXocę 웃 Пepeúpa ツ Avatar answered Oct 02 '22 21:10

ΦXocę 웃 Пepeúpa ツ