Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to use the Java 8 Stream API on Android API < 24?

I've read this post here. But still I cannot run code containing Java 8 Stream API features like the following on minSdkVersion < 24.

List<Car> newCars = cars.stream()                         .filter(s -> s.getColor().equals("red"))                         .collect(Collectors.toList()); 

This doesn't run due to the error message

Call requires API level 24 (current min is 15): java.util.Collection#stream

So does someone know a solution?

like image 306
unlimited101 Avatar asked Sep 15 '16 15:09

unlimited101


People also ask

Can I use Java 8 for Android?

Android does not support Java 8. It only supports up to Java 7 (if you have kitkat) and still it doesn't have invokedynamic, only the new syntax sugar. If you want to use lambdas, one of the major features of Java 8 in Android, you can use gradle-retrolamba.

Which version of Java streams API is introduced?

Introduced in Java 8, the Stream API is used to process collections of objects. A stream is a sequence of objects that supports various methods which can be pipelined to produce the desired result.

In which package Stream API of Java 8 is available?

All the Java Stream API interfaces and classes are in the java. util. stream package. Since we can use primitive data types such as int, long in the collections using auto-boxing and these operations could take a lot of time, there are specific classes for primitive types – IntStream , LongStream and DoubleStream .

What version of Java does Android use?

Java 8 source code that works in latest version of Android, can be made to work in older versions of Android.


Video Answer


1 Answers

[original answer]

You can not use Java8 streams on API level < 24.

However, there are some libraries that backport some of the stream functionality

https://github.com/aNNiMON/Lightweight-Stream-API

https://github.com/konmik/solid

https://sourceforge.net/projects/streamsupport/ (mentioned by @sartorius in comment)

[update k3b 2019-05-23]

https://github.com/retrostreams/android-retrostreams is a spinoff from streamsupport which takes advantage of Android Studio 3.x D8 / desugar toolchain's capability to use interface default & static methods across Jar file boundaries. There are also links to other android-retroXXX ie for CompletableFuture.

[update aeracode 2020-07-24]

Good news, now we can use Java 8 Stream API and more without requiring a minimum API level.

like image 95
Robert Estivill Avatar answered Oct 24 '22 11:10

Robert Estivill