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?
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.
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.
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.
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.
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.
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