What is and how functional interface works in java

Functional interface are an interface which represent some functionality. In java Runnable is an interface which contain some functions to run in thread operation so Runnable is a functional interface by definition.

functional interface in java 8 and its types

Functional interface are introduced in java8 even before java 8 we have few functional interfaces such as Runnable, Callable, Comparator.

Functional interfaces are also known as single abstract method (SAM) which mean the interface must contain only one abstract method in it and can contain default and static methods with its implementation but it cannot contain more than one abstract method in it.

How to create functional interface in java?

We can create a functional interface in java just like we used to create normal interface but annotate the interface with @FunctionalInterface its optional to add this annotation then what is the use of this annotation.@FunctionalInterface helps to ensure the interface is not containing more than one abstract method if it contains then the compiler will set ‘Unexpected @FunctionalInterface annotation’ message.

Adder is a functional interface with an abstract method add which take two parameters.


@FunctionalInterface
interface Adder {
	int add(int num1, int num2);
}
public class CustomFuctionalInterface {
	public static void main(String[] args) {
		Adder adder = (n1, n2) -> n1 + n2;
		int result = adder.add(5, 5);
		System.out.println("5+5 = " + result);
	}
}
Output: 
5+5 = 10

Let add one more abstract method to be Adder interface and try to run it


@FunctionalInterface
interface Adder {
	abstract int add(int num1, int num2);
	abstract int sub(int num1, int num2);
}
public class CustomFuctionalInterface {
	public static void main(String[] args) {
		Adder add = (n1, n2) -> n1 + n2;
		int result = add.add(5, 5);
		System.out.println("5+5 = " + result);
	}
}

Error:Invalid '@FunctionalInterface' annotation; Adder is not a functional interface.

Above error is due to the present of two abstract method in the interface since a functional interface should contain only one abstract method compiler is giving error.

The functional interface can also implement other interfaces if the interface doesn’t contain any abstract's method in it. If our interface has more than one abstract methods then the compiler will not allow us to create lambda expression for our interface.

Why we are using functional interface in java because its help us to enable lambda expression in code.

How functional interface help compiler to understand lambda?

When we write a lambda expression compiler check the interface and variable datatype.

Since the functional interface has only a single method its make compiler easy to understands what is the method input and output.

Functional interface and lambda expression help to achieve functional programming in java.

What are the new functional interfaces in java 8?

  • Predicate
  • Function
  • Consumer
  • Supplier

These functional interfaces are mainly used in java 8 collections and streams. All  functional interface are present inside java.util.function  package. Functional interface are generic one where it takes T and E value.

T: Indicate the Datatype

Predicate: It’s used to return boolean value based on conditions specified.


@FunctionalInterface 
public interface Predicate {
   public boolean test(T  t);
}
  

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);
		Predicate<Integer> isEven = n -> n % 2 == 0;
		numbers.stream().filter(isEven).forEach(number -> System.out.println(number));
	}
}
Output: 
2  

Function: It takes a single input parameter and return a single output value.


@FunctionalInterface 
public interface Function<t> {
    public <r> apply(T parameter);
}
 

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);
		Function<List<Integer>,Integer> sumFunction = num -> {
			int sum=0;
			for(Integer n:num) {
				sum=n+sum;
			}
			return sum;
		};
		System.out.println(sumFunction.apply(numbers));
	}
}
OutPut:
6  

Supplier : It doesn’t take any input but simply supply value (output) to the methods.


@FunctionalInterface 
public interface Supplier<T> { 
T get(); 
}
 

import java.util.function.Supplier;
public class SuppilerExample {
	public static void main(String[] args) {
		Supplier<Double> randomeValue = () -> Math.random();
		System.out.println("Random Value " + randomeValue.get());
	}
}
OutPut:
Random Value 0.01949190090919717
 

Consumer :  It takes single input parameter and perform operation on them without returning any value.

@FunctionalInterface 
public interface Consumer<T> { 
void accept(T t); 
}

import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;
public class ConsumerExample {
	public static void main(String[] args) {
		List<Integer> numbers = Arrays.asList(1, 2, 3);
		Consumer<Integer> display = num -> System.out.println(num);
		// Using above consumer function in foreach method
		numbers.stream().forEach(display);
	}
}
OutPut:
1
2
3

Post a Comment

Previous Post Next Post

Recent Posts

Facebook