Java 8, and I install new Android Studio 3.0.
Add code:
List<String> myList = Arrays.asList("a1", "a2", "b1", "c2", "c1");
myList
.stream()
.filter(s -> s.startsWith("c"))
.map(String::toUpperCase)
.sorted()
.forEach(System.out::println);
But I get compile error:
Call requires API level 24 (current min is 15) java.util.stream.Collection
While there is a bunch of Java 1.8 support in Android Studio 3.0 (lambdas, method references, default interface methods), not all of 1.8 is supported for all Android APIs. In particular, java.util.stream
is not supported until API 24.
See the developer docs: https://developer.android.com/studio/write/java8-support.html#supported_features
A good library to get backported Java 1.8 libraries such as java.util.stream
is StreamSupport: https://github.com/streamsupport/streamsupport
In order to use Streams and other java 8 API without requiring minimum API level 24, you need to do the following:
Upgrade Android Gradle Plugin to 4.0.0 or higher
classpath 'com.android.tools.build:gradle:4.0.0
Then add this dependency to your build.gradle file:
dependencies {
coreLibraryDesugaring 'com.android.tools:desugar_jdk_libs:1.0.6'
....
}
Finally Add this to your build.gradle file:
compileOptions {
// Flag to enable support for new language APIs
coreLibraryDesugaringEnabled true
targetCompatibility JavaVersion.VERSION_1_8
sourceCompatibility JavaVersion.VERSION_1_8
}
Enjoy Java 8 Streams and Time APIs :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With