Functional Interfaces - Java 8 In-Built


What is Functional Interface?

An Interface with single abstract method is called a Functional Interface.

Note: We can have other static or default methods. There is no restriction on it.

Why it is called as Functional Interface & what is it's purpose?

Functional interface gives us the ability to write the functional code like using lambda expressions making code shorter, cleaner and readable. Below is a example code


package test;

import java.util.List;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class FunctionalInterfaces {



    public static void main(String[] args){

        /* 1. Consumer  - Consumes & process ( 1 i/p - no o/p)
              void accept(T value)  */
        Consumer<Long> printInteger = a -> System.out.print(" " + a);

        /* 2. Predicate - tests & return boolean (1 i/p - boolean return)
              boolean test(T value)   */
        Predicate<Integer> isEven = a -> a%2==0;

        /* 3. Function  -  1 i/p  and 1 o/p
              R apply(T var1)  */
        Function<Integer, Long> squareNumber = a -> (long) (a * a);

        /* 4. Supplier ( only o/p)
              T get()  */
        Supplier<List<Integer>> integerList = () ->         IntStream.range(1,10).boxed().collect(Collectors.toList());


        integerList.get().stream()  // From Supplier got the list
                .filter(isEven) // filtered even numbers using Predicate
                .map(squareNumber) // squared using Function
                .forEach(printInteger); //printing using Consumer

    }

}        




N V S Santha Rao

Principal Consultant at Bharatiya Vidya Bhavan's

8 个月

Well said!

赞
回复

要查看或添加评论,请登录

社区洞察

其他会员也浏览了