๐ŸŽ‰ Special Offer !    Code: GET300OFF    Flat โ‚น300 OFF on every Java Course
Grab Deal ๐Ÿš€

Function Interface  


Introduction
  • Function interface is a functional interface in Java 8 that represents a function which takes one argument and produces a result.
  • It is part of the java.util.function package.
  • Uses of Function Interface:
    • Used to transform data from one type to another.
    • Commonly used in map() operations with streams.
    • Helps write clean, functional-style code using lambda expressions.
    • Can be chained with andThen() and compose() methods for multiple transformations.
  • Syntax :
    public interface Function
    {
        R apply(T t);
        //some default methods are also present
    }
Programs:
  • 1. Simple program without lambda expression:
    import java.util.function.Function;
    
    public class MainApp
    {
        public static void main(String[] args)
        {
            // Function to find square of a number using anonymous class
            Function<Integer, Integer> square = new Function<Integer, Integer>() {
                @Override
                public Integer apply(Integer x) {
                    return x * x;
                }
            };
    
            // Test numbers
            System.out.println("Square of 5 : " + square.apply(5));
            System.out.println("Square of 9 : " + square.apply(9));
        }
    }
  • 2. Program with lambda expression:
    import java.util.function.Function;
    
    public class MainApp
    {
        public static void main(String[] args)
        {
            // Function to find square of a number using lambda expression
            Function<Integer, Integer> square = x -> x * x;
    
            // Test numbers
            System.out.println("Square of 5 : " + square.apply(5));
            System.out.println("Square of 9 : " + square.apply(9));
        }
    }