Java 8 Features to start using in Android

Sharing is caring!

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

Similar Posts

Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Mayur kohli

Good article! worth reading information you have shared here on java 8 features to start using in android. Most of us just aware of java 8 features only but after reading this we got to know that how the way we can use java features in android.Thanks for sharing.