Press "Enter" to skip to content

Using LINQ in Android for all API levels with android-linq

vpandzic 0

If you have been C# developer who then started programming for Android you were amazed with the fact that Java is similar to C#, much more than new official language for Android development – Kotlin. However, soon you find out that you are missing something: possibility to manipulate collections in a elegant way, without using for loop inside loop inside loop.

Java 8 brings new stream API which is very similar to LINQ in a way that enables manipulating collections using less code and make it more readable (although this can depend if you are familiar with all operators LINQ or stream API has)

Let’ compare them in simple example:

var dataset = new [] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
// the .NET example
dataset.Where(x => x > 5).Sum();
// the Java example
data.stream().filter(x -> x > 5).mapToInt(Integer::intValue).sum();
// Result: 40

You can see this example or see others on the internet but what I found is that .NET code is more readable to me and often shorter. But, this could be due the fact that I program in .NET longer than in Java.

Anyway, if you want to use Java stream API in Android and also support Android version less than 7.0 what wou will probably want to you can’t. Support for stream API is dependant on Android API level so you can use all great things from Java 8 Stream API only if you are targetting Android 7.0 or Android 8.0 Oreo which is released today.

Luckily, there are few libraries on Github you can use that enable LINQ style of writing code.

Check this example:

List guestsToCheckOut= stream(evisitorGuests).where(x->x.getStatus().equals("CHECKEDIN")).toList();

It is known that in Java and Android you will write a lot of boilerplate code and this is great thing to make your code more readable and maintanable.

<h2>Android LINQ</h2>

Library is called android-linq and altought it doesn’t seem to much popular (at least by number of stars) it is great. Library has little to no impact on performance because it does not make use of reflection or proxies. It is easy to get started – just put this into your gradle file:

You will also need to setup Retrolambda for Android  but is mather of copying some code to your gradle file.

Lot of methods like first(), firstOrNull(), sum(), skip(), take(), aggregate(), count(), groupBy(), orderBy(), thenBy() are supported.

    Leave a Reply

    Your email address will not be published. Required fields are marked *