wal wal - 6 months ago 44
Java Question

cannot resolve Arrays.stream in android studio

I am trying to use a lambda expression in Android Studio to filter an array

String[] a = { "s", "", "1", "", "" };
a = Arrays.stream(a).filter(s -> !s.isEmpty()).toArray(String[]::new);

I am getting an error on compilation 'Cannot resolve method

enter image description here

Other Lambda expressions (say for click events) are working and I am targetting java 1.8 in my app gradle:

compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
incremental = false;

File -> Project Stucture
I am using the embedded JDK and even when I switch to the latest Java 8 JDK i still get the error.

Interestingly if i switch back to VERSION_1_7 then my prevously working lambda statements give a compile error.

How can I get this filter working in Android Studio?


There is a difference between Java8 language features and Java8-API. Android supports only a subset of each. Lambdas are a Java8 language feature. Whereas the stream API is an API introduced in the Java8-API.

Language feature are implemented by the compiler and might need some API-Support, whereas the Java-API needs to be present on the device.

This means you can use lambdas with apps having minSdkVersion < 24 but you can't use the stream API, since it is only part of the sdk for >=24.


You have the same in other "Java-technologies". Typically the Eclipse compiler can have a source compatibility of 1.8 and a target compatibility of 1.6, this would allow you to use lambdas, but not streams.