Predefined Functional interfaces

  • Last Updated: August 10, 2023
  • By: javahandson
  • Series
img

Predefined Functional interfaces

In this article, we will learn what are predefined functional interfaces. We will also learn the most commonly used predefined functional interfaces with proper examples.

 

The functional interface is an interface that contains only one abstract method. To know more about the functional interface you can check the article here. Predefined functional interfaces are the interfaces that are already defined in Java API’s.

There are many predefined functional interfaces defined in Java 8 to make lambda expressions the common programming norm. The predefined functional interfaces are present in java.util.function package. There are almost 43 predefined functional interfaces available in this package. We will learn about the most important and frequently used functional interfaces here.

Predicate interface

A Predicate interface is used to perform the conditional check. The Predicate interface is having an abstract method named test. This test method will accept an argument of type T and return a boolean.

@FunctionalInterface
public interface Predicate<T> {
   boolean test(T t);  // abstract method
}

Parameters: t is an input argument of type T ( means the predicate interface can work with any type )

Returns: boolean ( returns true if the condition matches else false )

1. Write a program to check if a number is an even number.

 

package com.javahandson.predefined;
import java.util.function.Predicate;

public class Test {
    public static void main(String[] args) {

        Predicate<Integer> predicate = number -> number % 2 == 0;
        System.out.println("10 is even number : "+predicate.test(10));
    }
}

Output : 10 is even number : true

In the above example, T is an Integer. We have passed an Integer argument to the test method of the Predicate interface. The Predicate returns a boolean by validating the even number logic.

2. Write a program to check if the Student’s marks are greater than 400

Firstly create a Student Class

package com.javahandson.predefined;

public class Student {
    String name;
    int marks;

    public Student(String name, int marks) {
        this.name = name;
        this.marks = marks;
    }

    public String getName() {
        return name;
    }

    public int getMarks() {
        return marks;
    }
}

Create a Test Class that will have a predicate to test if the Student’s marks are greater than 400.

package com.javahandson.predefined;
import java.util.function.Predicate;

public class Test {
    public static void main(String[] args) {

        Predicate<Student> predicate = student -> student.getMarks() > 400;

        Student student1 = new Student("Suraj", 450);
        Student student2 = new Student("Iqbal", 350);
        Student[] students = {student1, student2};

        for (Student student : students) {
            System.out.println(student.getName()+" is having marks greater than 400 : "+predicate.test(student));
        }
    }
}
Output : Suraj is having marks greater than 400 : true
         Iqbal is having marks greater than 400 : false

In the above example, T is a user-defined Student Class. We have passed a Student instance argument to the test method of the Predicate interface. The Predicate returns a boolean by validating if the Student’s marks are greater than 400 or not.

Function Interface

The Function interface is having an abstract method named apply. This apply method will accept an argument of type T perform an operation and return a value of type R.

Note* T can be of the same type as R or they can be different.

@FunctionalInterface
public interface Function<T,R> {
    R apply(T t); // abstract method
}

Parameters: t is an input argument of type T ( means the Function interface can work with any type )

Returns: R ( means the Function interface can return a value of any type )

1. Write a program to find the square of a given number

package com.javahandson.predefined;
import java.util.function.Function;

public class Test {
    public static void main(String[] args) {

        Function<Integer, Integer> function = number -> number * number;
        int result = function.apply(6);
        System.out.println("Square of given number is : "+ result);
    }
}

Output : Square of given number is : 36

In the above example, T is an Integer and R is also an Integer. We have passed an Integer argument to the apply method of the Function interface. The apply method squares the passed integer and returns the output as an Integer.

2. Write a program that takes the input as Student Object and returns Grade i.e String

package com.javahandson.predefined;
import java.util.function.Function;

public class Test {
    public static void main(String[] args) {

        Function<Student, String> function = student -> {
            if (student.getMarks() > 400) {
                return "Grade A Distinction";
            }
            return "Grade B First Class";
        };

        Student student1 = new Student("Suraj", 450);
        Student student2 = new Student("Iqbal", 350);

        Student[] students = {student1, student2};
        for (Student student : students) {
            System.out.println(student.getName()+" passed with : "+ function.apply(student));
        }
    }
}
Output : Suraj passed with : Grade A Distinction
         Iqbal passed with : Grade B First Class

In the above example, T is a Student and R is a String. We have passed a Student instance argument to the apply method of the Function interface. The Function returns a String i.e. Grade by validating if the Student’s marks are greater than 400 or not.

Consumer Interface

The Consumer interface is having an abstract method named accept. This accept method will accept an argument of type T performs an operation but it will not return any value. The return type is void.

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

Parameters: t is an input argument of type T ( means the Function interface can work with any type )

Returns: void ( nothing )

1. Write a program to find the square of given numbers and print it

package com.javahandson.predefined;
import java.util.function.Consumer;

public class Test {

    public static void main(String[] args) {

        Consumer<Integer> consumer = number -> {
            int result = number * number;
            System.out.println("Square of "+number+" is : "+result);
        };

        int[] numbers = {2, 3, 5};

        for (int number : numbers) {
            consumer.accept(number);
        }
    }
}

Output : Square of 2 is : 4
         Square of 3 is : 9
         Square of 5 is : 25

In the above example, T is an Integer. We have passed an Integer argument to the accept method of the Consumer interface. The accept method squares the passed integer and prints the output.

2. Write a program that takes the input as a Student and prints the student’s name

package com.javahandson.predefined;
import java.util.function.Consumer;

public class Test {
    public static void main(String[] args) {

        Consumer<Student> consumer = student -> System.out.println("Student name is : "+student.getName());

        Student student1 = new Student("Suraj", 450);
        Student student2 = new Student("Iqbal", 350);

        Student[] students = {student1, student2};
        for (Student student : students) {
            consumer.accept(student);
        }
    }
}

Output : Student name is : Suraj
         Student name is : Iqbal

In the above example, T is of Student type. We have passed a Student instance to the accept method of the Consumer interface. The accept method gets the Student’s name and prints it.

Supplier Interface

The Supplier interface is having an abstract method named get. This get method will not accept any argument but it performs an operation and return a value of type R.

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

Parameters: No input argument

Returns: R ( means the Supplier interface can return a value of any type )

1. Write a program to return the current date

package com.javahandson.predefined;
import java.util.Date;
import java.util.function.Supplier;

public class Test {
    public static void main(String[] args) {

        Supplier<Date> supplier = () -> new Date();
        System.out.println("Current date is : "+ supplier.get());
    }
}
Output : Current date is : Sun Jul 30 11:42:15 IST 2023

In the above example, R is of Date type. We are not passing any input argument to the get method. The get method calculates and returns the current date.

2. Write a program to print all the even numbers till 20

package com.javahandson.predefined;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Supplier;

public class Test {
    public static void main(String[] args) {

        Supplier<List<Integer>> supplier = () -> {
            List<Integer> list = new ArrayList();
            for (int i=1; i<=20; i++) {
                if (i % 2 == 0) {
                    list.add(i);
                }
            }
            return list;
        };
        System.out.println("List of even numbers : "+ supplier.get());
    }
}
Output : List of even numbers : [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]

In the above example, R is of List<Integer> type. The get method calculates all the even numbers till 20 add them to the list and returns it.

So this is about predefined functional interfaces in Java 8. I hope you like the article. If you are having any questions on this topic please raise them in the comments section.

Leave a Comment