Java 8 Predicate vs Function: A Comparison with Examples


Java 8 introduced several new features to enhance the language’s functional programming capabilities. Among these features are Predicates and Functions, both of which play vital roles in functional programming paradigms. In this blog post, we will explore the differences between Java 8 Predicates and Functions, providing examples to illustrate their usage and demonstrate their unique characteristics.

What are Predicates and Functions?

Predicates and Functions are functional interfaces introduced in Java 8’s java.util.function package. They enable the use of lambda expressions and method references to represent and manipulate behavior as data, bringing functional programming concepts into the Java language.

Posts you may like:

  1. Java 8- Find the Average of List of Integers
  2. Java 11- New Methods of String Class
  3. Java 8 Stream API allMatch(), anyMatch() and noneMatch() method Example

1. Predicates

The Predicate interface represents a single argument function that returns a Boolean value. It is commonly used for filtering and testing conditions. The Predicate functional interface defines a single abstract method: test(T t), where T is the input argument type.

Example: Filtering a List using a Predicate

PredicateExample.java
package org.websparrow;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;

public class PredicateExample {

	public static void main(String[] args) {
		
		List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);

		Predicate<Integer> evenPredicate = n -> n % 2 == 0;
		List<Integer> evenNumbers = filter(numbers, evenPredicate);

		System.out.println("Even numbers: " + evenNumbers);
	}

	public static List<Integer> filter(List<Integer> list, Predicate<Integer> predicate) {
		List<Integer> result = new ArrayList<>();
		for (Integer item : list) {
			if (predicate.test(item)) {
				result.add(item);
			}
		}
		return result;
	}
}

Output:

Even numbers: [2, 4, 6, 8, 10]

In this example, we define a Predicate called evenPredicate, which checks if a number is even. We use this predicate to filter out the even numbers from the list of integers.

2. Functions

The Function interface represents a function that takes one argument and produces a result. It is commonly used for transforming or mapping data. The Function functional interface defines a single abstract method: apply(T t), where T is the type of the input argument, and it returns a value of type R.

Example: Mapping a List using a Function

FunctionExample.java
package org.websparrow;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Function;

public class FunctionExample {

	public static void main(String[] args) {

		List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);

		Function<Integer, String> intToString = n -> "Number: " + n;
		List<String> numberStrings = map(numbers, intToString);

		System.out.println("Number strings: " + numberStrings);
	}

	public static List<String> map(List<Integer> list, Function<Integer, String> function) {

		List<String> result = new ArrayList<>();
		for (Integer item : list) {
			result.add(function.apply(item));
		}
		return result;
	}
}

Output:

Number strings: [Number: 1, Number: 2, Number: 3, Number: 4, Number: 5]

In this example, we define a Function called intToString, which converts an integer to a string representation. We use this function to map the list of integers to a list of strings representing each number.

3. Predicates vs Functions

  1. Purpose:
    • Predicates: Used for testing or filtering conditions.
    • Functions: Used for transforming or mapping data.
  2. Return Type:
    • Predicates: Return a boolean value (true or false).
    • Functions: Return a result of any desired type.
  3. Abstract Method:
    • Predicates: test(T t) – Evaluates the condition for a given input.
    • Functions: apply(T t) – Performs the transformation or mapping on the input.
  4. Usage:
    • Predicates: Often used with filtering operations, such as List filtering or stream operations.
    • Functions: Often used with mapping operations, such as transforming elements in a collection.
  5. Examples of Usage:
    • Predicates: Filtering a list of objects based on specific criteria or conditions.
    • Functions: Transforming one type of object to another, such as converting integers to strings or applying mathematical operations.

Summary

Java 8 Predicates and Functions are powerful functional interfaces that provide flexibility and conciseness when working with functional programming concepts in Java. Predicates are primarily used for filtering and testing conditions, while Functions are used for transforming and mapping data. By leveraging these functional interfaces, developers can write more expressive and concise code, making their programs more readable and maintainable.

References

  1. Interface Predicate<T> – Java Doc
  2. Interface Function<T,R> – Java Doc

Similar Posts

About the Author

Atul Rai
I love sharing my experiments and ideas with everyone by writing articles on the latest technological trends. Read all published posts by Atul Rai.