5

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?

2 Answers 2

6

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.

Sign up to request clarification or add additional context in comments.

5 Comments

You don't need 'stream'. The List has a forEach method directly on it
Simply foreach without stream
@tddmonkey and Yassin Hajaj: Thanks; I wasn't aware of that.
where did you find those information? I know java 8 support lamda but how do you know it can be used like this?
@user3659052: Java 8 added not only lambda function but the stream concept and a bunch of methods for manipulating them with lambdas, so you might want to read up on streams.
1

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.