我想遍历作用于每个项目的集合。
Collection<Listener> listeners = ....
interface Listener {
void onEventReceived();
void onShutDown();
}
代码可以是:
void notifyShutdown() {
for(Listener listener:listeners){
listener.onShutDown();
}
}
我想抓住java8 lambda,所以我声明了一个辅助接口:
interface WrapHelper<T> {
void performAction(T item);
}
和一个通知方法
public void notifyListeners(WrapHelper<Listener> listenerAction) {
for (Listener listener : listeners) {
listenerAction.performAction(listener);
}
}
所以我可以声明如下方法:
public void notifyEventReceived() {
notifyListeners(listener -> listener.onEventReceived());
}
public void notifyShutDown() {
notifyListeners(listener -> listener.onShutDown());
}
我的问题是:我是否需要声明接口WrapHelper
我自己,是因为android API <24中已经存在用于此目的的类。
谢谢
答案 0 :(得分:3)
是的,因为API <24不支持java.util的Consumer,所以您需要声明接口WrapHelper
不过,您可以使用Lighweight-Stream-API library,它提供了现成的类和接口,例如Supplier,Consumer和Optional。它的工作原理几乎与Java8的新功能相同,并且可以在API <24中正常工作。