Optimise conditional expression with Java 8 Predicates

Hi Folks,

When we do coding then it is very common need to evaluate conditions which yield to true and false. 

There can be many scenarios where we use to evaluate conditions as below:

  • String variable which needs to be verified for null or empty
  • A list of objects which needs to be verified for empty
  • An object which needs to be verified for null
  • Variable needs to be verified for equality with other

So for evaluating these kind of conditions we generally use logical operators like AND, OR, NOT or some basic operators.

For e.g. Let say there is a String which needs to be verified for null OR empty then following will be the logic for the same:

public static void main(String[] args) {

    System.out.println(System.currentTimeMillis());

    String str1 = args[0];

    if(str1 == null || str1.isEmpty())
    {
        System.out.println("String is empty or null");
    }
}

In this, we used operator with OR logical operator.

Now let’s think that if we want to evaluate conditions many times in our program then we’ll have to write these conditions everywhere where we want to evaluate condition.

Right??

What if we put all these conditions at one place and use them instead of writing conditions everywhere. By doing this following things will be happened:

  • Don’t need to write same condition everywhere
  • Less chances of writing wrong conditional expression
  • All the conditions will be at same place and will be tested once.

How to achieve it?

As we know that Java 8 comes with lot of interested features which leads to a functional programming. One of the most interesting feature is Predicate.

Predicate

Predicate is a functional interface and can therefore be used as the assignment target for a lambda expression or method reference. So we can use these true/false returning functions in day to day programming everywhere where we evaluate conditions.

To see java doc for Predicate click here.

Let’s understand how to create predicates and use those to evaluate our conditional expression.

Evaluate null or empty checks for a String.

public static Predicate isNullOrEmpty() {
    return str -> str == null || str.isEmpty();
}

Evaluate null or empty check for a list

public static Predicate isNullOrEmptyList() {
    return list -> list == null || list.isEmpty();
}

Evaluate object for a null

public static Predicate isNull() {
    return Objects::isNull;
}

Evaluate String for equal to some other string

public static Predicate isEqual()
{
    return str -> str.equalsIgnoreCase("anotherString");
}

Now it’s time to use predicates as below:

public class TestPredicates {

    public static Predicate isNull() {
        return Objects::isNull;
    }

    public static Predicate isEqual() {
        return str -> str.equalsIgnoreCase("anotherString");
    }

    public static Predicate isNullOrEmpty() {
        return str -> str == null || str.isEmpty();
    }

    public static Predicate isNullOrEmptyList() {
        return list -> list == null || list.isEmpty();
    }

    public static void main(String[] args) throws IOException {

        List list = new ArrayList();

        String a = args[0];

        if (isNullOrEmpty().test(a)) {
            System.out.println("Object is null");
        }

        if(isNullOrEmptyList().test(list))
        {
            System.out.println("List is null or empty");
        }

        if(isEqual().test(a))
        {
            System.out.println("String is equal");
        }

    }

}

Here we create predicates and use them in our program by executing test method of predicate to evaluate conditions.

As you can observe that we have put all our common conditions at one place and are using those everywhere where we want.

To know more about predicates read this.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s