top of page

Understanding Functional Interface

There are many new interesting features were introduced in Java – 8. Functional interface is one of those which has proven very useful for the programmers

. What is Functional Interface ?

Functional interface, which is a part of the java. util. function package, is an interface that contains single abstract method.



public interface FunctionalInterfaceExample { 
	public void doSomething();  
} 
	

The interface can also have a default and/or static method along with the unimplemented method.




public interface FunctionalInterfaceExample { 
   public void doSomething(); 
   public default void print(text){ 
   	System.out.println(text); 
   } 
} 
 

Why do we need Functional Interface?

Functional Interfaces and Lambda Expressions help us in writing smaller and cleaner code by avoiding writing lengthy codes for anonymous class implementation.

Types of Functional Interfaces.

Java has introduced few functional interfaces specifically designed for common scenarios to reduce coding for the programmers. Following are some of these built-in functional interfaces in Java. Function

Predicate

Consumer

Supplier

Let's see all of them with the example one by one. Function <T,R>

The Java Function interface (java.util.function.Function) is one of the most central functional interfaces in Java. In a common language we can say that Function interface is used to do the transformation. It can accepts one argument and produces a result.


 
public class FunctionExample { 
	public static void main(String args[]) { 
     	List<Integer> numbers = new ArrayList();	    					  
         numbers.add(10); 
         numbers.add(20); 
         Function<Integer, Integer> fun = i -> i / 2;      		 
         numbers.stream().map(fun).forEach(System.out::println);     
   } 
} 

The Function interface contains few methods, R apply(T t) is one of them and only one that is needed to be implemented. Others come with a default implementation, hence we do not have to implement those extra methods.


Here is a Function implementation example:

1) Traditional Approach


 public class FunctionExample implements Function<Integer, Integer>{
	public static void main(String args[]) {
		FunctionExample obj = new FunctionExample();
		Integer result = obj.apply(3);
		System.out.println("Square of No : "+ result);
	}

	@Override
	public Integer apply(Integer no) {
		return no*no;
	}
}

2) Using Lambda Expresion:


public class FunctionExampleLambda{
	public static void main(String args[]) {
		Function<Integer, Integer> square = (no)-> no*no;
		Integer result = square.apply(3);
		System.out.println("Square of No : "+ result);
	}
}

As its seen in the above examples approach-2 is more concise and precise in terms of logic and coding. Predicate<T>

Predicate interface, java.util.function.Predicate , is a simple interface that is used to test condition. It accepts single argument and returns true Or false. In simple terms we can say that if we want to test some condition we can use Predicate interface.



public class Main { 
    public static void main(String args[]) { 
        List<Integer> numbers = new ArrayList(); 
        numbers.add(3); 
        numbers.add(5); 
        numbers.add(10); 
        Predicate<Integer> pred = i -> i > 5; 
        numbers.stream().filter(pred).forEach(i->System.out.println(i)); 
    } 
} 

Predicate has one abstract method, along with few others, is test(). In order to use implement Predicate interface we need to implement its boolean test(T t) method.


Here is a Predicate implementation example:

1) Traditional Approach


 public class PredicateExample implements Predicate<Integer>{	
	public static void main(String args[]) {
		PredicateExample obj = new PredicateExample();
		boolean result = obj.test(-5);		
		System.out.println(result==true ? "Negetive":"Positive");
	}

	@Override
	public boolean test(Integer no) {
		return no < 0;
	}
}

 

2) Using Lambda Expresion:


public class PredicateExample {
	public static void main(String args[]) {
		Predicate<Integer> isNegetive = (no)-> no < 0;
		System.out.println(
				isNegetive.test(4) == true ? "Negetive" : "Positive");
	}
}

Consumer<T>

Consumer interface, java.util.function.Consumer, is a simple interface that is accepts single value and no result is returned. In simple terms we can say that if we want to print a value or write it to file we can use Consumer interface.


void accept(T t) is the method that is needed to be override in order to user Consumer Interface.

1) Traditional Approach


public class ConsumerExample implements Consumer<String>{
	public static void main(String args[]) {
		ConsumerExample obj = new ConsumerExample();
		obj.accept("i am transformed to uppercase");
	}

	@Override
	public void accept(String str) {
		System.out.println("Text transformation : "+str.toUpperCase()); 
	}
}

2) Using Lambda Expresion:


public class ConsumerExampleLambda {
	public static void main(String args[]) {
		Consumer<String> function = 
				(str) -> System.out.println(
						"Text transformation : " + str.toUpperCase());
		function.accept("i am transformed to uppercase");
	}
}

Supplier<T>

Supplier interface, java.util.function.Supplier, is a functional interface that represents an function that provides a value of some kind.


In simple terms Supplier interface is useful when we do not need to supply any kind of value but need some specific result in return eg. Some random number.


T get() is the method that is needed to be override in order to user Consumer Interface.

1) Traditional Approach


public class SupplierExample implements Supplier<Double> {
	public static void main(String args[]) {
		SupplierExample obj = new SupplierExample();
		System.out.println("Random number :"+ obj.get());
	}
	
	@Override
	public Double get() {
		return Math.random();
	}
}

2) Using Lambda Expresion:


public class SupplierExample {
	public static void main(String args[]) {
		Supplier<Double> function = () -> 10 * Math.random();
		System.out.println(function.get());
	}
}


27 views0 comments

Recent Posts

See All

Data Visualization Techniques Using Python

Introduction Data visualization is a crucial part of the data analysis process. It helps in understanding the data better and uncovering patterns, trends, and insights. Python provides several librari

bottom of page