Android

Java 8 Features to start using in Android

In this tutorial, I will explore to start using java 8 features in your project. I have seen many of developers they are not using the java 8 features in android. Probably they are thinking that Java is not giving any new feature. I would say for those people that Java is still not dead, a bunch of new features is added in version 8. Every android developer should start using the java 8 features as much as possible. Ok Sound Great:)

Let’s check what are the best java 8 features available to use in basic programming.

Lambda Expression

Lamba expression is added in java 8. Why should use the lambda expression? I would say there are many reasons to use this. We can easily distribute processing of collection over multiple threads. It is kind of block of code to execute. Let’s take an example for sorting the list of android versions by using Lambda expression.

prior Java 8:

List<String> versionList = Arrays.asList("Marshmallow", "Lolipop", "Kitkat", "Jelly Bean"); Collections.sort(versionList, new Comparator<String>() { @Override public int compare(String a, String b) { return b.compareTo(a); } });

Result after sort: Jelly Bean, Kitkat, Lolipop, Marshmallow

Now in java 8.

List<String> versionList = Arrays.asList("Marshmallow", "Lolipop", "Kitkat", "Jelly Bean"); Collections.sort(versionList, (String a, String b) -> { return b.compareTo(a); });

That is very less code now wow. Even We can make more short.

List<String> versionList = Arrays.asList("Marshmallow", "Lolipop", "Kitkat", "Jelly Bean");
Collections.sort(versionList, (String a, String b) -> b.compareTo(a));

Wow, Lambda is the amazing feature.  Let’s check another java 8 feature.

Method and Constructor References

Java 8 provide the option to pass references to methods or constructors via the: : keyword.  Let’s check an example, How we can pass reference constructor? Below example, I have a class TestJava with method startsWith to get the first character from my String.

public class TestJava { String startsWith(String s) { return String.valueOf(s.charAt(0)); } }

In java 8 we can call by using the converter to convert via the : : keyword.

TestJava testJavaObj = new TestJava(); Converter<String, String> converter = testJavaObj::startsWith; String converted = converter.convert("Android"); System.out.println(converted); // A

 

Let’s see how the : : keyword works for constructors. First, we define an example class name MobileDevices with different constructors.

public class MobileDevices { String deviceName; String platform; MobileDevices() {} MobileDevices(String deviceName, String platform) { this.deviceName = deviceName; this.platform = platform; } }

 

and we need to create the interface factory for MobileDevices to create the Object of same.

interface MobileDeviceFactory<M extends MobileDevices> {
    M create(String deviceName, String platform);
}

Now we can create the object of Mobile devices based on Mobilefactory via reference constructor.  Java compiler automatically chooses the right constructor for signature to create the object.

MobileDeviceFactory<MobileDevices> mobileFactory = MobileDevices::new;
MobileDevices mobile = mobileFactory.create("Google Pixel", "Android");

Predicates

Predicates are popular in mathematic, it is kind of function which is return a boolean value. Let’s see an example of predicate keyword used in java collection.

public class MobileDevices {
    String deviceName;
    String platform;
    int version
 
    MobileDevices() {}
 
    MobileDevices(String deviceName, String platform, int version) {
        this.deviceName =deviceName;
        this.platform = platform;
        this.version = version;
    }
}

Suppose I have many devices having different platform and version. I want to access the list of valid devices. For ex: I need only those devices which are Android version 5 or higher. Ok Cool:) Let’s see how we can filter by using filter keyword.

import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;
public class MobileDevicePredicates
{
    public static Predicate<MobileDevices> isAndroidVersionHigher5() {
        return p -> p.getVersion() > 5 && p.getPlatform().equalsIgnoreCase("Android");
    }
  public static List<MobileDevices> filterMobileDevices (List<MobileDevices> mobileDevices, Predicate<MobileDevices> predicate) {
        return mobileDevices.stream().filter( predicate ).collect(Collectors.<MobileDevices>toList());
    }
}

Wow, I am loving java 8 now. This makes new kind of programming in Java World.

Streams

A stream represents a sequence of elements and supports a different kind of operations to perform computations upon those elements. What does mean of a different kind of operation?  Here is the list of operations that can be done by the stream.

1.  Filter

2. Sorted

3. Map

4. Match

5. count

Ok That’s fine. Let’s see an example of streams to do the above operations.  Suppose I have a list of devices as below code.

List<String> devices = new ArrayList<>();
devices.add("android M");
devices.add("android L");
devices.add("android K");
devices.add("iOS 7");
devices.add("iOS 8");
devices.add("iOS 6");
devices.add("bbb2");
devices.add("android J");

Let’s say I want to filter only those devices which name start with “a” character.  So I use filter operation on the streams. A filter is an immediate operation which enables us to call another stream operation (forEach) on the result.

devices.stream()
    .filter((s) -> s.startsWith("a"))
    .forEach(System.out::println);

Great: Now I have a list of devices which are android platform based. But I want this list as a sorted. So we can use sorted operation on stream.

devices.stream()
    .sorted()
    .filter((s) -> s.startsWith("a"))
    .forEach(System.out::println);

Now I got the sorting device’s names on the list. I want to all names should be in uppercase. I need to use Map operation. Let’s see how?

devices.stream()
    .map(String::toUpperCase)
    .sorted((a, b) -> b.compareTo(a))
    .forEach(System.out::println);

Through the match operation, we can check any devices is matching which name start with “i” character. Let’s check.

boolean anyStartsWithI = devices.stream().anyMatch((s) -> s.startsWith("i"));
// true

We can count the number of devices which are start with “a”  by using the count operation.

long startsWithA =
        devices.stream()
        .filter((s) -> s.startsWith("a"))
        .count();
 
System.out.println(startsWithA);    // 4

Greate. Awesome Java 8 feature. In my next tutorial,  we will learn and understand Java 8 stream and Rx Observable in Rxjava2 and RxAndroid.

Happy weekend all. Enjoy 😉

0 0 votes
Article Rating
Java 8 Features to start using in Android

Recent Posts

Hide your production API key or any sensitive data in Android

Hi everyone, In this article, we are going to learn how to hide the production… Read More

1 year ago

How to handle the localisation or multi language support in android with examples?

Hello everyone, Today in this article, we are going to learn about localisation to support… Read More

2 years ago

How to convert any callback to Coroutines and use them in Kotlin Android?

Hello everyone, In this article, we are going to learn something to handle the callback… Read More

2 years ago

Request Permission Launcher with Kotlin in Android

In this article, we are learning about the run time permissions for request permission launchers.… Read More

2 years ago

Implement the SMS User Consent API and SMS Retriever API in Android

Hello everyone. In my last tutorial, we learned about the Jetpack Compose introduction and about applying the… Read More

2 years ago

Jetpack Compose Coroutine flow with LiveData/ViewModel in Android

Hello everyone, In this article, we are going to learn about the Jetpack Compose with… Read More

2 years ago