【问题标题】:How to wrap a object in a lambda in Android API <24如何在 Android API <24 中将对象包装在 lambda 中
【发布时间】:2018-12-12 17:26:35
【问题描述】:

我想迭代一个作用于每个项目的集合。

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

【问题讨论】:

  • 我不了解Android API,但是您可以访问JDK8的java.util.function.Consumer吗?这将对应于您的WrapHelper
  • 有很多选项,例如java-supportLWSandroid-retrostreams。仅举几例。

标签: java android java-8 functional-programming


【解决方案1】:

是的,你需要声明你的接口 WrapHelper,因为 API

不过,您可以使用Lighweight-Stream-API library,它提供了现成的类和接口,例如供应商、消费者和可选。它与 Java8 的新特性几乎相同,并且在 API

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多