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

JavaAndroidJava 8Java Stream

Java Problem Overview


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?

Java Solutions


Solution 1 - Java

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

Solution 2 - Java

Since release 8.2 of DexGuard it is possible to use the Java 8 streams API also on Android devices < API level 24. In order to do so, one needs to include the streamsupport library and DexGuard will translate all Java 8 stream API calls to the provided library. No additional handling is needed, and developers can simply code using the provided Java 8 streams API. Dependencies are also translated automatically, so it is possible to use libraries with Java 8 features also for Android development.

This feature will also be included in ProGuard in the near future, stay tuned.

Edit: Proguard 6.1.0 for which there already exists a beta version supports backporting Java 8 stream and time API.

Solution 3 - Java

Yes, it is! Starting from AGP 4.0.0 we can use Stream API and some other Java 8+ APIs (e.g. java.time)

Minimal required changes to your app's build.gradle:

android {
  compileOptions {
    // Flag to enable support for the new language APIs
    coreLibraryDesugaringEnabled true
  }
}

dependencies {
  coreLibraryDesugaring 'com.android.tools:desugar_jdk_libs:1.0.9'
}

Solution 4 - Java

Might be a little late to the party, but I just saw that If we use java8.util.stream.StreamSupport then we can run the same functional programming approach and use it prior to Api 24. Eg taken from web3j -

StreamSupport.stream(transactionReceipt.getLogs())
            .map(log -> extractEventParameters(event, log))
            .filter(Objects::nonNull)
            .collect(Collectors.toList());

Solution 5 - Java

Another solution I like to use is to statically use Kotlin's extensions over Collections from Java code, if the project supports both of course:

List<Car> newCars = CollectionsKt.filter(cars, s -> s.getColor().equals("red"));

Same for .map, .reduce, .first, ...etc

Solution 6 - Java

Create a İnterface.

public interface Pre<T,R> {
            R get(T item);
        }

Create a Filter Method.

public static  <T> List<T> Filter(List<T> list, Pre<T,Boolean> pre) {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
        {
            return list.stream().filter(p -> pre.get(p)).collect(Collectors.toList());
        }
        else
        {
            List<T> col = new ArrayList<T>();
            for (int i = 0 ; i < list.size() ; i++)
                if (pre.get(list.get(i)))
                    col.add(list.get(i));
            return col;
        }
    }

Using Code

    public static class model {
            public String Name;
        }
List<model> models = new ArrayList<>();
            ...
            List<model> filtermodels = Filter(models,p-> p.Name.equals("filter"));

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionunlimited101View Question on Stackoverflow
Solution 1 - JavaRobert EstivillView Answer on Stackoverflow
Solution 2 - JavaT. NeidhartView Answer on Stackoverflow
Solution 3 - JavaaeracodeView Answer on Stackoverflow
Solution 4 - JavaAbhriya RoyView Answer on Stackoverflow
Solution 5 - Javay.allamView Answer on Stackoverflow
Solution 6 - JavaYusuf AydınView Answer on Stackoverflow