Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AndroidStudio 3.0: Java 8 stream not compile (Call requires API level 24)

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
like image 278
Alexei Avatar asked Oct 31 '17 19:10

Alexei


2 Answers

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

like image 194
vonWippersnap Avatar answered Nov 17 '22 20:11

vonWippersnap


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 :)

like image 11
thejufo Avatar answered Nov 17 '22 21:11

thejufo