2

Functional Interfaces In Java8

 2 years ago
source link: https://blog.knoldus.com/functional-interfaces-in-java8/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client
Reading Time: 2 minutes

Hello readers, as you have visited here, you must be aware of Interfaces in Java. Before Java 8, all methods defined in an interface are public and abstract by default. After Java 8, there were certain enhancements in interfaces. Amongst all the enhancements in Java 8, one of them is “Functional Interface”.

What are Functional Interfaces?

In Java, the term functional interface refers to those interfaces which have exactly one abstract method. In addition to that abstract method, they can have any number of default and static methods in them. If you want to know about static and default methods, you can refer to JournalDev’s Article on static method and default method. The functional interfaces are also known as “Single Abstract Method (SAM) interfaces”.

Annotating these interfaces with @FunctionalInterface helps IDE or compiler to interpret them at development-time, or by the framework at run-time.

@FunctionalInterface interface FuncInterface{ void abstractMethod(); default void defaultMethod(){ //optional default method with some default implementation } static void staticMethod(){ //optional static method with some implementation } }

Functional Interface with respect to Inheritance

If an interface with no abstract method extends a functional interface, then the extended interface will also be considered as functional interface as shown in the example below:

@FunctionalInterface interface FuncInt1{ void abstractMethod(); }

@FunctionalInterface interface Funcint2 extends FuncInt1{ }

Again, if an interface with exactly one abstract method extends a functional interface with the same method signature, then the extended interface will also be considered as functional interface. Here’s an example below:

@FunctionalInterface interface FuncInt1{ void abstractMethod(String var); }

@FunctionalInterface interface Funcint2 extends FuncInt1{ void abstractMethod(String var); }

Predefined Functional Interfaces

The concept of functional interfaces was introduced in Java 8, but they were present before Java 8 also. Some of them are:

  • Runnable – void run();
  • Callable<V> – V call();
  • Comparable – int compareTo(T var1);

After Java 8, java.util.function package was introduced which includes some predefined interfaces. We will discuss them one by one below:

Predicate<T>

Predicate interface is used to check for a boolean value based on our given condition. If the condition satisfied with the given input, it returns true, else false. Predicate accepts an argument T and returns a boolean value.

Abstract method: boolean test(T var);

//This will return true if the passed integer is even
Predicate<Integer> p = (i) -> i % 2 == 0;

Function<T, R>

Function interface is used to perform some operation on the given input and returns some output. Function accepts an argument T and returns R.

Abstract method: R apply(T var)

//This will return the length of passed string argument
Function<String,Integer> f = String::length;

Consumer<T>

Consumer interface is used when we want to accept some input and perform some operation. It does not return anything. Mostly used for printing some content. Consumer accepts an argument T and performs the provided operation without returning anything.

Abstract method: void accept(T var)

//This will print the passed argument 'string'
Consumer<String> c = System.out::println;

Supplier<T>

Supplier interface is used when we want to return some value without giving any inputs. It does not take any arguments and return an object T.

Abstract method: T get()

//This will return the system date
Supplier<LocalDate> s = () -> LocalDate.now();
A Sample Code for printing the list of students with their roll number, name, marks and grade using the predefined functional interfaces below:

import java.util.Arrays; import java.util.List; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Predicate; import java.util.function.Supplier;

class Student { //roll number assigner used by supplier static int rollNoAssigner; //student properties int rollNo; String name; int marks; String grade;

//for initializing student with name and marks Student(String name, int marks) { this.name = name; this.marks = marks; } }

class FunctionalInterface { public static void main(String[] args) { //Function used to assign grades to students Function<Student, String> getGrade = student –> { String grade = ""; if (student.marks > 90) grade = "A"; else if (student.marks > 80) grade = "B"; else if (student.marks > 70) grade = "C"; else if (student.marks > 60) grade = "D"; else if (student.marks > 50) grade = "E"; else grade = "F"; return grade; }; //Supplier used to supply roll number to the student on FIFO basis Supplier<Integer> assignRollNo = () –> ++Student.rollNoAssigner;

//Predicate used to filter students whose marks is greater than 80 Predicate<Integer> filterStudent = marks –> marks >= 80;

//Consumer used to print student details Consumer<Student> printStudents = student –> { student.rollNo = assignRollNo.get(); student.grade = getGrade.apply(student); System.out.println("RollNo : " + student.rollNo); System.out.println("Name : " + student.name); System.out.println("Marks : " + student.marks); System.out.println("Grades : " + student.grade + "\n"); };

List<Student> list = Arrays.asList(new Student("divyanshu", 78), new Student("akash", 61), new Student("aditya", 43), new Student("jatin", 94), new Student("yatharth", 88)); for (Student student : list) { if (filterStudent.test(student.marks)) { printStudents.accept(student); } } } }

References :

After going through the contents, now you’ll be familiar with functional interfaces in java. Still, if you have any queries, feel free to contact me at [email protected].

Thank you for sticking to the end. If you like this blog, please do show your appreciation by giving thumbs ups and share this blog and give me suggestions on how I can improve my future posts to suit your needs. Follow me to get updates on different technologies


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK