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 RunnableCallableComparatorActionListener, 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.



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值