How Function Interfaces Work in Java 8?

In this post, I will use a simple example to illustrate how function interfaces work in Java 8.

1. Simple Example of Stream.filter()

The following code can be used to filter a list of strings by specifying the string’s length.

package com.programcreek.java8.stream;
 
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;
 
public class Java8Filter {
 
	public static void main(String[] args) {
		List<String> list = new ArrayList<String>();
		list.add("java");
		list.add("php");
		list.add("python");
		list.add("lisp");
		list.add("c++");
 
		//filter function
		Stream<String> stream = list.stream().filter(p -> p.length() > 3);
		String[] arr = stream.toArray(String[]::new);
 
		System.out.println(Arrays.toString(arr));
	}
}

2. What is Function Interfaces

A functional interface is an interface with a single abstract method. The Java API has many one-method interfaces such as Runnable, Callable, Comparator, ActionListener, etc.

Let’s take a look at the signature of the filter() method of Stream:

Stream<T> filter(Predicate<? super T> predicate);

From the method signature of filter(), the lambda expression p -> p.length() > 3 should be an instance of Predicate. The Predicate interface has one abstract method:

boolean test(T t)

Because of the object-oriented feature of Java, everything should be an object. So behind the scene, the lambda expression is converted to an object of functional interface.

3. Implementation of Object of Functional Interface

You may be curious about how the object of the function interface – Predicate – look like. We can guess the possible implementation of filter() method:

Stream<T> filter(Predicate<? super T> predicate){
	for (each string in stream){
	 	if(predicate.test(string)){
	 		keep the string
	 	}else{
	 		drop the string
	 	}
 
	return stream;
}

The predicate object is converted from the given lambda expression.

There are also other functional interfaces defined. Check out the java.util.function package to see the complete list.

Leave a Comment