9

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
Alexei
  • 14,350
  • 37
  • 121
  • 240
  • 3
    That's expected behavior. A min SDK level of API 15 corresponds to Ice Cream Sandwich, 4.0.3. A 6 year old runtime on a device can't magically support new Java 8 *API* that didn't exist when it was originally created. What you get with AS 3.0 (for minSDK < 24) is support for (a lot of) Java 8 *language* features (e.g. interface default methods), but not for the new Java 8 *API* (on such old devices). – Sartorius Oct 31 '17 at 23:19

2 Answers2

13

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

thejufo
  • 133
  • 1
  • 7
9

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

vonWippersnap
  • 483
  • 3
  • 9
  • Also not support "try resources". Show message: "Try-with-resources requires API level 19 (current min is 15)". – Alexei Nov 13 '17 at 08:21
  • Well that is just plain nonsense. Why are they calling it Java 8 if they don't abide by the standard?! – hrs May 09 '20 at 20:39