Java Tutorials


Java Functional Interfaces

    Java 8 introduced Lambda Expressions, These expressions depends on Functional Interfaces. A Functional Interface is an Interface which has only one Abstract method, and also it can have static and default methods. It can optionally be decorated with @FunctionalInterface Annotation.

Earlier java(i.e before JDK8) , an interfaces can be implemented using class/anonymous class. An anonymous class is a class which has no class name, and can implement interface methods.

Functional interfaces can be used as a return type for lambda expressions and method references.

Supplier functional iterfaces, which takes no input amd returns Result. Supplier functional interfaces has one abstract generic method called get

Java Framework Built-in Supplier Functional Interfaces.

     Java Supplier functional interfaces categorized into 2 types, 1. to support primitive types, 2. to support Generic Types

  • Supplier<T> to support Generic Type

  • Following Functional interfaces supports Primitive-type
  • IntSupplier
  • LongSupplier
  • DoubleSupplier
  • BooleanSupplier

Supplier Interfaces has one abstract method called get

     	T   get()
     


Usage of Supplier Functional Interfaces

  • Overloaded logging methods
  • Finding first element in the collection
  • Completable future
  • Optional object

Supplier Interface example

 	import java.util.function.*
 	
 	IntSupplier intSup = () -> {return 500;}
 	
 	intSup.getAsInt();   // returns 500
 	
 	
 	DoubleSupplier  dubSup = ()-> {return Math.random();}

System.out.println(dubSup.getAsDouble());
0.4991964608619356

System.out.println(dubSup.getAsDouble());
0.47916779058164016

System.out.println(dubSup.getAsDouble());
0.8797546609922758
 

Get File Length using Supplier Interface

	String file = "Countries.txt";
	
	Supplier<Long> fileSupplier = () ->{
				File f = new File(file);
				
				return f.length();
			}
	
	//Calling supplier interface get method		
       fileSupplier.get()   // returns file size.			

ADS