Java – How to wrap objects in lambda in Android API <24

How to wrap objects in lambda in Android API <24... here is a solution to the problem.

How to wrap objects in lambda in Android API <24

I want to iterate over collections that act on each project.

Collection<Listener> listeners = ....

interface Listener {

void onEventReceived();

void onShutDown();
}

The code can be:

void notifyShutdown() {
    for(Listener listener:listeners){
        listener.onShutDown();
    }
}

I

want to capture java8 lambdas so I declare a secondary interface:

interface WrapHelper<T> {
    void performAction(T item);
}

and a notification method

public void notifyListeners(WrapHelper<Listener> listenerAction) {
    for (Listener listener : listeners) {
        listenerAction.performAction(listener);
    }
}

So I can declare such a method:

public void notifyEventReceived() {
    notifyListeners(listener -> listener.onEventReceived());
}

public void notifyShutDown() {
    notifyListeners(listener -> listener.onShutDown());
}

My question is: do I need to declare the interface WrapHelper myself, since there are already classes for this purpose in Android API <24.

Solution

Yes, you need to declare an interface WrapHelper, because API<24 does not support consumers from java.util

However, you can use Lighweight-Stream-API library Wich provides ready-made classes and interfaces such as Supplier, Consumer, and Optional. It works pretty much the same as the Java8 new features and works well in API < 24.

Related Problems and Solutions