Predefined Functional Interfaces

Introduction

In the last blog, we learned about lambda expressions and functional interfaces. In this post, we will learn about predefined Functional Interfaces.

Predefined Functional Interfaces

  • Consumer FI

Consumer is an inbuilt functional interface introduced in Java 8.

Consumer can be used in all contexts where an object needs to be consumed i.e taken as input, and some operation is to be performed on the object without returning any result.

Syntax:- void accept(T t)

Code Example:

public class ConsumerDemo {

    public static void main(String[] args) {
        Consumer<Integer> consumer=(t)->{
            System.out.println("Printing :"+t);
        };

        consumer.accept(10); //o/p:- Printing : 10

        List<Integer> list1= Arrays.asList(1,2,3,4);
        list1.stream().forEach(consumer);
        //o/p:-
        //Printing : 1
        //Printing : 2
        //Printing : 3
        //Printing : 4
    }
}

  • Predicate FI

This functional interface is used for conditional checks. It is used where we have to use true/false returning functions in day-to-day programming.

Syntax: boolean test(T t);

Code Example:


public class PredicateDemo {
    public static void main(String[] args) {
        Predicate<Integer> predicate=(t)->t % 2 ==0 ;

        System.out.println(predicate.test(5)); //o/p:- false

        List<Integer> list1= Arrays.asList(1,2,3,4);
        list1.stream().filter(predicate).forEach(t-> System.out.println("print Even: "+ t));
        //o/p:-
        // print Even: 2
        // print Even: 4
    }
}

  • Supplier FI

    Suppliers can be used in all contexts where there is no input but output is expected.

    Example:- T get();

    Code Example:

public class SupplierDemo {

    public static void main(String[] args) {

        Supplier<String> supplier=()->{
            return "Hi! Java Blog readers";
        };

        System.out.println(supplier.get()); //o/p: Hi! Java Blog Readers
    }
}

Summary

In this post, we have learned about Predefined Functional Interfaces

Thank you for reading. If you found this article helpful, react and share. Cheers.