Java Tutorial

Java Tutorial Java Features C++ vs Java Java History Java Hello World Java Development Kit Java Runtime Environment Java Virtual Machine Difference between JDK, JRE, and JVM Memory Areas in Java Java Operators Java Keywords Primitive Data Types Variables

Java Loops

Java Do While Loop Java While Loop Java For Loop Java Enhanced For Loop

Java Programs

Java Basic Programs Factorial Program in Java Fibonacci Series Program in Java Prime Number Program in Java Palindrome Number Program in Java Armstrong Number Program in Java Anagram Program in Java Pattern Programs in Java Calculator Program in Java Leap Year Program in Java Addition Program in Java Number Pattern Programs in Java Star Pattern Programs in Java Package Program in Java Pyramid Program in Java Sorting Program in Java String Palindrome Program in Java Even Odd Program in Java For Loop Program in Java If Else Program in Java Switch Case Program in Java GCD Program in Java LCM Program in Java Hello Program in Java Matrix Program in Java Menu Driven Program in Java Series Program in Java Client Server Program in Java Swapping Program in Java Pig Latin Program in Java Tower of Hanoi Program in Java Recursion Program in Java Matrix Multiplication Program in Java Perfect Number Program in Java Classes and Objects in Java Example Programs String Programs in Java Array Programs in Java Constructor Program in Java Inheritance Program in Java Abstract class Program in Java Interface Program in Java Encapsulation Program in Java Polymorphism Program in Java Exception Handling Program in Java Multithreading Program in Java Thread Program in Java Collection Programs in Java ArrayList Program in Java Stack Program in Java Applet Program in Java Swing Program in Java JDBC Program in Java How to run Java program in command prompt How to run Java program in Eclipse

Java Sorting

Sorting Algorithms in Java Merge Sort in Java Quick Sort in Java Bubble Sort in Java Insertion Sort in Java Selection Sort in Java Heap Sort in Java Radix Sort in Java Topological Sort in Java Bucket Sort in Java Counting Sort in Java

Java OOPs Concepts

OOPs - Object Oriented Programming Objects and Classes in Java Java Naming Conventions Constructors in Java Java this keyword Java static keyword Inheritance in Java Aggregation in Java Java super keyword Constructor Chaining and Constructor Overloading Java Polymorphism Static and Dynamic Binding in Java Java Abstraction Abstract class in Java Interface in Java Difference between Abstract class and Interface Java final keyword Packages in Java Access Modifiers in Java Java Wrapper classes Java Numbers Java Characters Java Integer Java Boolean Java Arrays Java Command Line Arguments Java strictfp Keyword Java Math

Java Strings

Java Strings Java String Methods StringBuilder in Java StringBuffer in Java Java Regular Expressions StringBuffer vs StringBuilder String vs StringBuffer String vs StringBuilder String Manipulation in Java Java String Concatenation How to Reverse a String in Java String Array in Java How to Compare Two Strings in Java How to Concatenate Two Strings in Java Why String in Immutable in Java java.lang.NumberFormatException for Input String String Pool in Java Java Generate Random String How to take String Input in Java Java String Interview Questions

Java Exceptions

Exception Handling in Java Java try catch Java throw Java throws Difference between throw and throws Java finally Java Custom Exception Java Exception Propagation

Garbage Collection

Automatic Resource Management in Java Java Garbage Collection Java finalize() Java gc() Difference between final, finally and finalize

Multithreading

Multithreading in Java Process and Thread in Java Basic Terms in Multithreading Java Thread creation Thread Scheduler in Java Java Thread class DeadLock in Java

Java IO

Java IO Java Read File Java BufferedWriter Java InputStreamReader Java File Java Read File Line By Line Java FileOutputStream Jar File in Java

Serialization

Java Serialization Java transient

Networking

Java Network Programming Java Socket Programming Java URL Java URLConnection HttpURLConnection in Java Java InetAddress Java DatagramSocket and Java DatagramPacket

AWT

Java AWT

Swing

Swing in Java

Java Collections

Collections in Java Java List Interface ArrayList in Java LinkedList in Java Vector in Java Stack in Java ArrayList vs LinkedList in Java ArrayList vs Vector in Java Java Set Interface HashSet in Java LinkedHashSet in Java TreeSet in Java Java Queue Interface PriorityQueue in Java ArrayDeque in Java Java Map Interface HashMap in Java LinkedHashMap in Java TreeMap in Java Dictionary in Java Hashtable in Java Properties in Java Collections class in Java Java Comparable Java Comparator Comparable vs Comparator in Java

Java Generics

Generics in Java

Java Annotations

Annotations in Java

Java JDBC

Java JDBC Tutorial

Java Differences

Java vs JavaScript Python vs Java Kotlin vs Java Java vs C++ C# vs Java Static vs Non-static in Java C vs Java int vs Integer in Java Stack vs Heap in Java Java Array vs ArrayList

How to

How to run Java program How to set path in Java How to check the Java version in cmd How to install Java in Windows 10 How to run Java program in cmd How to call a method in Java How to sort an array in Java How to iterate HashMap in Java How to write Java program How to create an array in Java How to create a package in Java How to generate random numbers in Java How to input String in Java How to create thread in Java How to find length of String in Java How to sort a string in Java How to use scanner in Java How to achieve multiple inheritance in Java How to run Java program in Eclipse How to call a function in Java How to create array of objects in Java How to create custom exception in Java How to achieve abstraction in Java How to call static method in Java

Java 8 Features

Java 8 Features Lambda Expressions in Java Functional Interface in Java Streams in Java Java Base64 Encoding and Decoding Parallel Arrays Sort in Java

Java 9 Features

Java 9 Tutorial Java 9 Try With Resources Java 9 Interface Private Method

Java Servlet Tutorial

Java Servlets Tutorial

Java JSP Tutorial

Java JSP Tutorial

Hibernate Tutorial

Hibernate Tutorial

Spring Tutorial

Spring Tutorial

Spring MVC Tutorial

Spring MVC Tutorial

Jenkins Tutorial

Jenkins Tutorial

Java Math Methods

Math.abs() Math.acos() Math.addExact() Math.asin() Math.atan () Math.atan2() Math.cbrt() Math.ceil() Math.copysign() Math.cos() Math.cosh() Math.decrementExact() Math.exp() Math.expm1() Math.floor() Math.floorDiv() Math.floorMod() Math.getExponent() Math.hypot() Math.IEEEremainder() Math.incrementExact() Math.log() Math.log10() Math.log1p() Math.max() Math.min() Math.multiplyExact() Math.multiplyFull() Math.negateExact() Math.nextAfter() Math.nextDown() Math.nextUp() Math.pow() Math.random() Math.rint() Math.round() Math.scalb() Math.signum() Math.sin() Math.sinh() Math.sqrt() Math.subtractExact() Math.tan() Math.tanh() Math.toDegrees() Math.toIntExact() Math.toRadians() Math.ulp()

Java String Methods

toCharArray() copyValueOf() endsWith() equals() equalsIgnoreCase() format() getBytes() getChars() hashCode() indexOf() intern() isEmpty() join() lastIndexOf() length() replace() replaceAll() replaceFirst() split() startsWith() subSequence() substring() toLowerCase() toUpperCase() trim() valueOf()

Java Conversion

Java Convert String to int Java Convert int to String Java Convert String to long Java Convert long to String Java Convert String to float Java Convert float to String Java Convert String to double Java Convert double to String Java Convert String to Date Java Convert Date to String Java Convert String to Object Java Convert Object to String Java Convert String to char Java Convert char to String Java Convert int to long Java Convert long to int

Misc

Functional Interfaces in Java Singleton class in Java Awesome explanation of Strings in Java Object class in Java Static class in Java All the important string methods in Java String Handling Method in Java What are Array strings in Java Advantages and Disadvantages of Strings in Java Big Decimal class in Java Class definition in Java Char and String differences in Java Difference between String, StringBuffer and StringBuilder in java Replace character in string Java String Coding Interview Questions in Java What is String in Java? String isnullorempty in Java String Matches in Java Trim Method in String Java Bean class in Java Libraries in Java Arithmetic Operations on String in Java

Functional Interfaces in Java

Java has forever remained an Object-Oriented Programming language. By object-oriented programming language, we can declare that everything present in the Java programming language rotates throughout the Objects, except for some of the primitive data types and primitive methods for integrity and simplicity.

Functions in the Java programming language are part of a class, and if someone wants to use them, they have to use the class or object of the class to call any function.

Functional Interface is additionally recognized as Single Abstract Method Interfaces. In short, they are also known as SAM (Single Abstract Method) interfaces. Functional interfaces in Java are the new feature that provides users the approach of fundamental programming.

Functional interfaces are included in Java SE 8 with Lambda expressions and Method references in order to make code more readable, clean, and straightforward. It ensures that they include precisely only one abstract method. It is used and executed by representing the interface with an annotation called @FunctionalInterface. As described earlier, functional interfaces can contain only one abstract method. However, they can include any quantity of default and static methods. 

In Functional interfaces, there is no need to use the abstract keyword as it is optional to use the abstract keyword because, by default, the method defined inside the interface is abstract only. We can also call Lambda expressions as the instance of functional interface.

Example of Functional Interfaces in Java

public interface MyFunctionalInterface1 {


    public void execute();


}

The above is an example of a functional interface in Java because it only contains only a single method, and there is no implementation inside that method. Usually, in a Java functional interface, there are no implementations of the method or process which is declared inside it. However, it can contain the implementations of the default methods and static methods which are displayed inside it. 

Following is another instance of the functional interface in Java, with implementations of some of the methods, i.e., static and default methods:

public interface MyFunctionalInterface2{


    public void execute();


    public default void print(String msg) {
        System.out.println(msg);
    }


    public static void print(String msg, PrintWriter writer) throws IOException {
        writer.write(msg);
    }


}

In the above example, the interface MyFunctionalInterface2 is still counted as a functional interface because it comprises mainly a single abstract method (non-implemented method).

Some Built-in Java Functional Interfaces

Since Java SE 1.8 onwards, there are many interfaces which are converted into the functional interface. All these interfaces are annotated with @FunctionalInterface. These interfaces are as follows:

  • Runnable: It contains only the run() method.
  • Comparable: It contains only the compareTo() method.
  • ActionListener: It contains only the actionPerformed() method.
  • Callable: It contains only the call() method.

Java SE 8 included four types of functional interfaces in Java that can be applied in multiple situations. These are:

  1. Consumer
  2. Predicate
  3. Function 
  4. Supplier

Amidst the previous four interfaces, the first three interfaces, i.e., Consumer, Predicate, and Function, likewise have additions that are provided beneath:

  1. Consumer: Bi-Consumer
  2. Predicate: Bi-Predicate
  3. Function: Bi-Function, Unary Operator, Binary Operator 

Consumer:

The consumer interface of the functional interface is the one that accepts only one argument or a gentrified argument. The consumer interface has no return value. It returns nothing. There are also functional variants of the Consumer — DoubleConsumer, IntConsumer, and LongConsumer. These variants accept primitive values as arguments. 

Other than these variants, there is also one more variant of the Consumer interface known as Bi-Consumer. 

Bi-Consumer:

Bi-Consumer is the most exciting variant of the Consumer interface. The consumer interface takes only one argument, but on the other side, the Bi-Consumer interface takes two arguments. Both, Consumer and Bi-Consumer has no return value. It also returns noting just like the Consumer interface. It is used in iterating through the entries of the map. 

Syntax / Prototype of Consumer Functional Interface:

Consumer<Integer> consumer = (value) -> System.out.println(value);

The above implementation of the Java Consumer functional interface prints the value passed as a parameter to the print statement. This implementation uses the Lambda function of Java.

Predicate:

In scientific logic, a function that accepts an argument and, in return, generates a boolean value as an answer is known as a predicate.

Similarly, in the Java programming language, a predicate functional interface of Java is a type of function which accepts a single value or argument and does some sort of processing on it, and returns a boolean (True/ False) answer. The implementation of the Predicate functional interface also encapsulates the logic of filtering (a process that is used to filter stream components on the base of a provided predicate) in Java.

Just like the Consumer functional interface, Predicate functional interface also has some extensions. These are IntPredicate, DoublePredicate, and LongPredicate. These types of predicate functional interfaces accept only primitive data types or values as arguments.  

Bi-Predicate:

Bi-Predicate is also an extension of the Predicate functional interface, which, instead of one, takes two arguments, does some processing, and returns the boolean value.

Syntax of Predicate Functional Interface:

public interface Predicate<T> {


    boolean test(T t);


}

The predicate functional interface can also be implemented using a class. The syntax for the implementation of predicate functional interface using a class is given below - 

public class CheckForNull implements Predicate {


    @Override
    public boolean test(Object o) {


        return o != null;


    }
}

The Java predicate functional interface can also be implemented using Lambda expressions. The example of implementation of Predicate functional interface is given below - 

Predicate predicate = (value) -> value != null;

The above implementation of functional interfaces uses Lambda expressions that is manageable and effective than the one implemented by using a class. As both the implementations are doing the same work, i.e., returning the same output.

Function:

 A function is a type of functional interface in Java that receives only a single argument and returns a value after the required processing. There are many versions of Function interfaces because a primitive type can’t imply a general type argument, so we need these versions of function interfaces. Many different versions of the function interfaces are instrumental and are commonly used in primitive types like double, int, long. The different sequences of these primitive types are also used in argument.

These versions are:

Bi-Function:

The Bi-Function is substantially related to a Function. Besides, it takes two arguments, whereas Function accepts one argument. 

The prototype and syntax of Bi-Function is given below:

@FunctionalInterface
public interface BiFunction<T, U, R> 
{


   R apply(T t, U u);
    ……...


}

In the above code of interface, T, U are the inputs, and there is only one output that is R. 

Unary Operator and Binary Operator:

There are also two other function interfaces which are named as Unary Operator and Binary Operator. They both extend the Function and Bi-Function, respectively. In simple words, Unary Operator extends Function and Binary Operator extends Bi-Function. 

The prototype of the Unary Operator and Binary Operator is given below:

1. Unary Operator:

@FunctionalInterface
public interface UnaryOperator<T> extends Function<T, U> 
{
    ……...
}

2. Binary Operator:

@FunctionalInterface
public interface BinaryOperator<T> extends BiFunction<T, U, R> 
{
    ……...
}

We can understand front the above example that the Unary Operator accepts only one argument and returns a single argument only. Still, in Unary Operator both the input and output values must be identical and of same type. 

On the other way, Binary Operator takes two values and return one value comparable to Bi- Function but similarly like Unary Operator, the input and output value type must be identical and of same type.

Supplier:

The Supplier functional interface is also a type of functional interface that does not take any input or argument and yet returns a single output. The kind of functional interface is generally used in the lazy generation of values. Supplier functional interfaces are also used for defining the logic for the generation of any sequence.

For example, the logic behind the Fibonacci Series can be generated with the help of the Stream.generate method that is implemented by the Supplier functional Interface. 

The different extensions of the Supplier functional interface hold many other supplier functions like BooleanSupplier, DoubleSupplier, LongSupplier, and IntSupplier. The return type of all these further specializations is their corresponding primitives only. 

Syntax / Prototype of Supplier Functional Interface is:

@FunctionalInterface
public interface Supplier<T>{


// gets a result
………….


// returns the specific result
…………


T.get();


}

The java.util.function package includes many different functional interfaces that are managed by JDK and can be used by and available for end-users. The interfaces described in this package are also annotated with @FunctionalInterface annotation.

There are many other functional interfaces in Java other than the one which are described above. These functional interfaces are also part of the java.util.function package. These are:

  • BooleanSupplier: It signifies a type of supplier functional interface that returns boolean-valued results.
  • DoubleBinaryOperator: It depicts an operation on two operands of type double and returns a value of double type. 
  • DoubleConsumer: It signifies an operation that accepts a single argument of type double and no result is returned.
  • DoubleFunction<R>: It portrays a function that takes a value of type double and returns a specified result.
  • DoublePredicate: It describes a boolean-valued function (which is also known as the predicate) of an argument of type double. 
  • DoubleSupplier: It signifies a type of supplier functional interface of double type.
  • DoubleToIntFunction: It denotes a function that receives an argument of type double and gives a result of type int. 
  • DoubleToLongFunction: It denotes a function that receives an argument of type double and gives a result of type long. 
  • DoubleUnaryOperator: It describes an operation on a single operand of type double and gives a result of type double.
  • IntBinaryOperator: It signifies an operation on two operands of type int and produces a result of type int.
  • IntConsumer: It signifies an operation that accepts a single argument of type int and no result is returned.
  • IntFunction<R>: It portrays a function that accepts an argument of type int and returns a specified result.
  • IntPredicate: It describes a boolean-valued function (which is also known as the predicate) of an argument of type int.
  • IntSupplier: It signifies a type of supplier functional interface of int type.
  • IntToDoubleFunction: It denotes a function that receives an argument of type int and gives a result of type double.
  • IntToLongFunction: It denotes a function that receives an argument of type int and gives a result of type long.
  • IntUnaryOperator: It denotes a process on only one operand of the type int and result returned is also of type int.
  • LongBinaryOperator: It represents a process on two operands of type long and which returns a long type result.
  • LongConsumer: It signifies a process that accepts only one value of type long and here no result is returned.
  • LongFunction<R>: It portrays a function that accepts an argument of type long and returns a specified result.
  • LongPredicate: It describes a boolean-valued function (which is also known as the predicate) of an argument of type long.
  • LongSupplier: It signifies a type of supplier functional interface of long type.
  • LongToDoubleFunction: It denotes a function that receives an argument of type long and gives a result of type double.
  • LongToIntFunction: It denotes a function that receives an argument of type long and gives a result of type int.
  • LongUnaryOperator: It denotes a process on only one operand of the type long and result returned is also of type long.
  • ObjDoubleConsumer<T>: It describes an operation that takes an argument of type double and an object and returns no result.
  • ObjIntConsumer<T>: It describes an operation that takes an argument of type int and an object and returns no result.
  • ObjLongConsumer<T>: It describes an operation that takes an argument of type long and an object and returns no result.
  • ToDoubleBiFunction<T, U>: It signifies a function that receives two values and the result returned is of type double.
  • ToDoubleFunction<T>: It describes a function that provides a result of type double. 
  • ToIntBiFunction<T,U>: It signifies a function that receives two values and the result returned is of type int.
  • ToIntFunction<T>: It describes a function that provides a result of type int.
  • ToLongBiFunction<T,U>:  It signifies a function that receives two values and the result returned is of type long.
  • ToLongFunction<T>: It describes a function that provides a result of type long.

These are the different functional interfaces in Java other than the usual ones. 

Examples of Functional Interfaces in Java 

Now it’s time to see different examples of Java functional interfaces and also their expression and their uses in the Java programming language.

Example 1 - In example 1, let us see the use of java.util.function.function and its built-in functional interface.

FunctionalInterfaceExample1.java

import java.util.function.*;
  
    public static void main (String args[]){
        
        FunctionalInterfaceExample1 obj = new FunctionalInterfaceExample1();
        
        Integer sq= obj.apply(10);
        
        System.out.println("Square of 10 is " + sq);
    }


public class FunctionalInterfaceExample1 implements Function<Integer, Integer>{
    
    @Override
    public Integer apply (Integer x){
    
        return x*x;
    
    }
}

Output: 

Square of 10 is 100

In the above code, we are implementing the following interface in the class. It is present in the java.util.function package.

Interface: 

package java.util.function;


public interface Function<T,R>{


public <R> apply(T inputparams);


}

Example 2 - In the example 2, let us see how functional interfaces in Java are designed using lambda expressions.

FunctionalInterfaceExample2.java

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


Runnable r = () -> {System.out.println ("Thread running.....");};


// above creating an instance of functional interface


new Thread(r).start(); 


}
}

Output:

Thread running.....

In the above code, we have applied and used the Java Lambda expressions in order to implement the functional interfaces in Java.

Example 3 - In this example 3, let us see the performance of another built-in functional interface known as Consumer interface in Java to traverse through a List.

FunctionalInterfaceExample3.java

import java.util.function.*;
import java.util.*;
 
public class FunctionalInterfaceExample3{
    
    public static void main (String args[]){
        
        ArrayList<Integer> arr = new ArrayList<Integer>();
        
        arr.add(1);
        arr.add(2);
        arr.add(3);
        arr.add(4);
        arr.add(5);
        arr.add(6);
        
        // Iterate arraylist using consumer
        arr.forEach(new Consumer<Integer>(){
            
            @Override
            public void accept(Integer item){
                
                System.out.println(item);
                
            }
        });
    }
}

Output - 

1
2
3
4
5
6

Example 4 - In this example, let us see the performance of another built-in Predicate functional interface in Java to iterate a List using Lambda Expressions.

FunctionalInterfaceExample4.java

import java.util.*;
import java.util.function.Predicate;
  
public class FunctionalInterfaceExample4
{
    public static void main(String args[])
    {
  
        ArrayList<String> people = Arrays.asList("Ram","Shyam","Ramesh","Suresh","Anupam");
  
      // using Java Lambda expressions to create an object of type Predicate<String>
        Predicate<String> p = (n)->n.endsWith("m");
  
        // Iterating through all the members of list
        for (String str:people)
        {
            // calling the method test
            if (p.test(str))
                System.out.println(str);
        }
    }
}

Output:

Ram
Shyam
Anupam

Points to Remember

Here are some significant points regarding Functional interfaces in Java:

  • In functional interfaces, there is only one abstract method supported. If the annotation of functional interface, i.e., @FunctionalInterface is not implemented or written with a function interface, more than one abstract method can be declared inside it. However, in this situation with more than one functional interface, that interface will not be called a functional interface. It is called a non-functional interface.
  • There is no as such need of the @FunctionalInterface annotation as it is voluntary only. This is written because it helps in checking compiler level. Besides this, it is optional.
  • An infinite number of methods (whether static or default) can be added in the functional interface. In simple words there is no limit of a functional interface containing static and default methods.
  • Overriding methods from the parent class do not violate the rules of a functional interface in Java.

Conclusion 

The above content or article provides a precise knowledge and processing of the Java functional interfaces. The significant benefit of using functional interfaces of the Java SE 8 is that it allows for support for lambda expressions. It support helps in eliminating a lot of redundant code. Java functional interfaces and lambda expressions together helps in writing of small, efficient, and cleaner code.

Functional interfaces in Java also helps in making the code more precise and straight forward.



ADVERTISEMENT
ADVERTISEMENT