Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Android desugar Java 8 Iterable.forEach() with minSdkVersion<24?

I was very excited hearing about Google's desugar project since I have to support minSdkVersion 17.

I went ahead and tried a simple Java 8 example:

List<String> myList = Arrays.asList("element1","element2","element3");
myList.forEach(element -> System.out.println(element));

However, Android Studio says Call requires API level 24 (current min is 17): java.lang.Iterable#forEach

Google issued a table about what features are supported. Does their documentation mention whether or not Iterable.forEach() is supported in any minSdkVersion?

like image 756
OneWorld Avatar asked Nov 12 '19 09:11

OneWorld


People also ask

What does the forEach () method on Iterable do?

The forEach() method performs the given action for each element of the Iterable until all elements have been processed or the action throws an exception.

Does Android support Java 8?

Java 8 language features are now supported by the Android build system in the javac/dx compilation path. Android Studio's Gradle plugin now desugars Java 8 class files to Java 7-compatible class files, so you can use lambdas, method references and other features of Java 8.

What is desugaring Android?

Through a process called API desugaring, the DEX compiler (D8) allows you to include more standard language APIs in apps that support older versions of Android.

Is forEach better than for loop Java?

forEach() can be implemented to be faster than for-each loop, because the iterable knows the best way to iterate its elements, as opposed to the standard iterator way. So the difference is loop internally or loop externally.


Video Answer


1 Answers

forEach uses a type from java.util.function which is only supported (with desugaring) on API level 24 or higher.

There are libraries that add support for streams. See this answer for more info.

like image 106
JensV Avatar answered Oct 11 '22 09:10

JensV