Is there a way to use Java 8 functional interfaces on Android API below 24?

北慕城南 提交于 2019-12-05 00:00:58

Not sure if you still need an answer to this question, but others (like myself) might.

As version 3.0, Android Studio natively supports lambda functions and many other Java 8 functions on all API levels, but some (like Functional Interfaces and java.util.function) are still restricted to APIs 24+.

Until that support is expanded, android-retrostreams provides backport support for most of it. This project is an 'upgraded port' of the streamsupport library, which you can also use and has many of the functionalities in android-retrostreams. The streamsupport library supports down to Java 6/7, so you can use it even if you don't have AS 3.0+ or aren't targeting Java 8, but you're probably better off using android-retrostreams in most cases, if you can. You can go through the project's javadocs to see exactly what's offered, but highlights that I've used are java.util.function and java.util.Comparator.

Note that java in the package names is replaced with java9, and some of the class and/or method names may have been changed slightly. For example:

java.util.function becomes java9.util.function,

while

java.util.Comparator becomes java9.util.Comparators (and with slightly different method names and call patterns - but the same functionality).

For alternative, Lightweight-Stream-API also provides backport support. Like android-retrostreams metioned above, you have to replace some package names by using:

com.annimon.stream.function instead of java.util.function

com.annimon.stream.ComparatorCompat instead of java.util.Comparator

Android support library(AndroidX) now has Consumer and Supplier:

sadly only these two interfaces gets added as of writing.

Now we have Kotlin, it doesn't require you to specify the functional interface explicitly:

    fun test() {
        val text = withPrintStream {
            it.println("Header bla bla ")
            it.printf("%s, %s, %s,", "a", "b", "c").println()
        }
    }

    // Equivalent to the following code in Java:
    //     Consumer<PrintStream> action;
    //     action.accept(ps);
    fun withPrintStream(action: (PrintStream) -> Unit): String {
        val byteArrayOutputStream = ByteArrayOutputStream()
        val ps = PrintStream(byteArrayOutputStream)
        action(ps)
        ps.flush()
        return byteArrayOutputStream.toString()
    }
allprojects {
    repositories {
        maven { url 'https://jitpack.io' }
    }
}
dependencies {
        compile 'com.github.ipcjs:java-support:0.0.3'
}

code: ipcjs/java-support

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!