Open In App

Match Lambdas to Interfaces in Java

Last Updated : 17 Jan, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

One of the most popular and important topics is lambda expression in java but before going straight into our discussion, let us have insight into some important things. Starting off with the interfaces in java as interfaces are the reference types that are similar to classes but containing only abstract methods. This is the definition of interface we had before java 1.8.  As before java version 1.8, we are using any version, interfaces are of three types namely as listed below s follows:

  • Normal Interface
  • Interface with multiple methods.
  • Marker interface (Interfaces does not contain any methods).

From 1.8 all  SAM (Single Abstract Method) interfaces is called as Functional Interface.

Functional Interface: Functional interface is an interface that contains exactly one abstract method but the important point is to remember that it can have any number of default or static methods along with the object class methods, as this confuses programmers the most.

Example:

Java




// Java Program to Illustrate Functional Interface
 
// Importing required classes
import java.io.*;
 
// Interface
@FunctionalInterface
interface display {
 
    // Attribute
    void show(String msg);
 
    // Method
    // To compute the sum
    default int doSum(int a, int b) { return a + b; }
}
 
// Main class implementing the above interface
class GFG implements display {
 
    // Overriding the existing show() method
    @Override
 
    public void show(String msg)
    {
 
        // Print message
        System.out.println(msg);
    }
 
    // Main driver method
    public static void main(String[] args)
    {
 
        // Creating object of class inside main()
        GFG object = new GFG();
 
        // Calling show() method in main()
        object.show("Hello World!");
 
        // Print statement
        System.out.println(object.doSum(2, 3));
    }
}


Output

Hello World!
5

Furthermore, now let us discuss which is anonymous classes. Anonymous class is only creating for one-time use, we cannot reuse it. The question that must be wondering that why do we need such type of class? Some scenarios, like when our only purpose is to override a method you can use it. Now, another advantage of it is, with the help of this we can instantiate the interface very easily.

Example: Suppose you want to book a cab 

Java




// Java Program to Illustrate Functional Interface
// With the Usage of Anonymous class
 
// Importing input output classes
import java.io.*;
 
// Interface
@FunctionalInterface
interface Cab {
 
    void bookCab();
}
 
// Main class
class GFG {
 
    // Method 1
    // Main driver method
    public static void main(String[] args)
    {
 
        // Creating object of above functional interface
        Cab cab = new Cab() {
            // Method 2
            // Overriding above bookCab() method
            @Override public void bookCab()
            {
 
                // Print statement
                System.out.println(
                    "Booking Successful!! Arriving Soon!!");
            }
        };
 
        cab.bookCab();
    }
}


Output

Booking Successful!! Arriving Soon!!

Now is the right time to discuss lambda expressions in java. It is one of the important features of Java 8. In fact, Lambda expressions are the fundamental approach to functional programming in Java. It is an anonymous function that does not have a name and does not belong to any class This in itself is a big topic that has been discussed before. And you must have an idea about it before you know what we are talking about.

Now we are done with discussing all concepts prior to landing upon how can we match lambda expression with the interface?

  • Lambda expression only works with functional interfaces in java.
  • Lambda expression provides a clear and concise way to represent a method interface via an expression.
  • It provides the implementation of a functional interface and simplifies software development.
  • We can easily remove the boilerplate code with the help of the Lambda expression.

Syntax:  

Parameter  -> expression body

Let us see our code in a different way because we have already seen an anonymous class example before as here we create a list of integers and we want to sort them based on their last digit.

Example 

Java




// Java Program Without Using Lambda Expression
 
// Importing all utility classes
import java.util.*;
 
// Main class
class GFG {
 
    // main driver method
    public static void main(String[] args)
    {
 
        // Creating an List of integer type
        List<Integer> list = Arrays.asList(
            234, 780, 451, 639, 456, 98, 75, 43);
 
        // Printing List before sorting
        System.out.println("Before Sorting");
 
        for (int i : list)
            System.out.print(i + " ");
 
        System.out.println();
 
        // Comparator is a functional interface
        // which is helps to sort object
        Collections.sort(list, new Comparator<Integer>() {
            // Overriding the existing compare method
            @Override
            public int compare(Integer a1, Integer a2)
            {
 
                return a1 % 10 > a2 % 10 ? 1 : -1;
            }
        });
 
        // Printing the list after sorting
        System.out.println("After Sorting");
 
        for (int i : list)
            System.out.print(i + " ");
 
        System.out.println();
    }
}


Output

Before Sorting
234 780 451 639 456 98 75 43 
After Sorting
780 451 43 234 75 456 98 639 

Characteristics of Lambda Expression 

  • Optional type declaration
  • Optional parenthesis around parameters.
  • Optional curly braces for one line of code.
  • Optional return keyword.

Lambda expression can take parameter just like method.

Example 1 Lambda expression with zero parameter 

Java




import java.io.*;
 
interface Display{
  void show();
}
 
class GFG{
   
  public static void main(String[] args){
   
    Display display= ()->System.out.println("Welcome");
     
    display.show();
      
  }
}


Output

Welcome

Example 2: Lambda Expression with Multiple Parameter

Java




// Java Program to Illustrate Lambda Expression
// with Multiple Parameter
 
// Importing required classes
import java.util.*;
 
// Main class
class GFG {
 
    // main driver method
    public static void main(String[] args)
    {
 
        // Creating a List of integer type
        List<Integer> list
            = Arrays.asList(24, 346, 78, 90, 21, 765);
 
        // Printing before sorting
        System.out.println("Before sorting.");
 
        for (int i : list)
            System.out.print(i + " ");
 
        System.out.println();
 
        // Sort the integers based on second digit
        Collections.sort(list, (a1, a2) -> {
            return a1 % 10 > a2 % 10 ? 1 : -1;
        });
 
        // Printing after sorting
        System.out.println("After sorting.");
 
        for (int i : list)
            System.out.print(i + " ");
 
        System.out.println();
    }
}


Output

Before sorting.
24 346 78 90 21 765 
After sorting.
90 21 24 765 346 78 

 



Previous Article
Next Article

Similar Reads

Callback using Interfaces in Java
Callback in C/C++ : The mechanism of calling a function from another function is called “callback”. Memory address of a function is represented as ‘function pointer’ in the languages like C and C++. So, the callback is achieved by passing the pointer of function1() to function2().Callback in Java : But the concept of a callback function does not ex
4 min read
Private Methods in Java 9 Interfaces
Java 9 onwards, you can include private methods in interfaces. Before Java 9 it was not possible. Interfaces till Java 7 In Java SE 7 or earlier versions, an interface can have only two things i.e. Constant variables and Abstract methods. These interface methods MUST be implemented by classes which choose to implement the interface. // Java 7 progr
4 min read
Why Java Interfaces Cannot Have Constructor But Abstract Classes Can Have?
Prerequisite: Interface and Abstract class in Java. A Constructor is a special member function used to initialize the newly created object. It is automatically called when an object of a class is created. Why interfaces can not have the constructor? An Interface is a complete abstraction of class. All data members present in the interface are by de
4 min read
Generic Constructors and Interfaces in Java
Generics make a class, interface and, method, consider all (reference) types that are given dynamically as parameters. This ensures type safety. Generic class parameters are specified in angle brackets “<>” after the class name as of the instance variable. Generic constructors are the same as generic methods. For generic constructors after th
5 min read
Interfaces and Polymorphism in Java
Java language is one of the most popular languages among all programming languages. There are several advantages of using the java programming language, whether for security purposes or building large distribution projects. One of the advantages of using JA is that Java tries to connect every concept in the language to the real world with the help
6 min read
Which Java Types Can Implement Interfaces?
In Java there is no concept of multiple-inheritance, but with the help of interface we can achieve multiple-inheritance. An interface is a named collection of definition. (without implementation) An interface in Java is a special kind of class. Like classes, interface contains methods and members; unlike classes, in interface all members are final
7 min read
Types of Interfaces in Java
In Java, an interface is a reference type similar to a class that can contain only constants, the method signatures, default methods, and static methods, and its Nested types. In interfaces, method bodies exist only for default methods and static methods. Writing an interface is similar to writing to a standard class. Still, a class describes the a
6 min read
How to Implement Multiple Inheritance by Using Interfaces in Java?
Multiple Inheritance is a feature of an object-oriented concept, where a class can inherit properties of more than one parent class. The problem occurs when methods with the same signature exist in both the superclasses and subclass. On calling the method, the compiler cannot determine which class method to be called and even on calling which class
2 min read
Interfaces and Inheritance in Java
A class can extend another class and can implement one and more than one Java interface. Also, this topic has a major influence on the concept of Java and Multiple Inheritance. Note: This Hierarchy will be followed in the same way, we cannot reverse the hierarchy while inheritance in Java. This means that we cannot implement a class from the interf
7 min read
Access modifiers for classes or interfaces in Java
In Java, methods and data members can be encapsulated by the following four access modifiers. The access modifiers are listed according to their restrictiveness order. 1) private (accessible within the class where defined) 2) default or package-private (when no access modifier is specified) 3) protected (accessible only to classes that subclass you
1 min read
Interfaces in Java
An Interface in Java programming language is defined as an abstract type used to specify the behavior of a class. An interface in Java is a blueprint of a behavior. A Java interface contains static constants and abstract methods. What are Interfaces in Java?The interface in Java is a mechanism to achieve abstraction. Traditionally, an interface cou
11 min read
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. There are no solely functions present in a
10 min read
Scanner match() method in Java with Example
The match() method of java.util.Scanner class returns the match result of the last scanning operation performed by this scanner. Syntax: public MatchResult match() Return Value: This function returns a match result for the last match operation. Exceptions: The function throws IllegalStateException if no match has been performed, or if the last matc
2 min read
How to Create Interfaces in Android Studio?
Interfaces are a collection of constants, methods(abstract, static, and default), and nested types. All the methods of the interface need to be defined in the class. The interface is like a Class. The interface keyword is used to declare an interface. public interface AdapterCallBackListener { void onRowClick(String searchText); } public interface
4 min read
Access specifier of methods in interfaces
In Java, all methods in an interface are public even if we do not specify public with method names. Also, data fields are public static final even if we do not mention it with fields names. Therefore, data fields must be initialized. Consider the following example, x is by default public static final and foo() is public even if there are no specifi
1 min read
Two interfaces with same methods having same signature but different return types
Java does not support multiple inheritances but we can achieve the effect of multiple inheritances using interfaces. In interfaces, a class can implement more than one interface which can't be done through extends keyword. Please refer Multiple inheritance in java for more. Let's say we have two interfaces with same method name (geek) and different
2 min read
Difference Between java.sql.Time, java.sql.Timestamp and java.sql.Date in Java
Across the software projects, we are using java.sql.Time, java.sql.Timestamp and java.sql.Date in many instances. Whenever the java application interacts with the database, we should use these instead of java.util.Date. The reason is JDBC i.e. java database connectivity uses these to identify SQL Date and Timestamp. Here let us see the differences
7 min read
Java AWT vs Java Swing vs Java FX
Java's UI frameworks include Java AWT, Java Swing, and JavaFX. This plays a very important role in creating the user experience of Java applications. These frameworks provide a range of tools and components for creating graphical user interfaces (GUIs) that are not only functional but also visually appealing. As a Java developer, selecting the righ
11 min read
Java.io.ObjectInputStream Class in Java | Set 2
Java.io.ObjectInputStream Class in Java | Set 1 Note : Java codes mentioned in this article won't run on Online IDE as the file used in the code doesn't exists online. So, to verify the working of the codes, you can copy them to your System and can run it over there. More Methods of ObjectInputStream Class : defaultReadObject() : java.io.ObjectInpu
6 min read
Java.lang.Class class in Java | Set 1
Java provides a class with name Class in java.lang package. Instances of the class Class represent classes and interfaces in a running Java application. The primitive Java types (boolean, byte, char, short, int, long, float, and double), and the keyword void are also represented as Class objects. It has no public constructor. Class objects are cons
15+ min read
Java.lang.StrictMath class in Java | Set 2
Java.lang.StrictMath Class in Java | Set 1More methods of java.lang.StrictMath class 13. exp() : java.lang.StrictMath.exp(double arg) method returns the Euler’s number raised to the power of double argument. Important cases: Result is NaN, if argument is NaN.Result is +ve infinity, if the argument is +ve infinity.Result is +ve zero, if argument is
6 min read
java.lang.instrument.ClassDefinition Class in Java
This class is used to bind together the supplied class and class file bytes in a single ClassDefinition object. These class provide methods to extract information about the type of class and class file bytes of an object. This class is a subclass of java.lang.Object class. Class declaration: public final class ClassDefinition extends ObjectConstruc
2 min read
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap also contains functions that support retrieval and deletion at both, high and low end of values and hence give a lot of flexibility in applicability and daily use. This function is poll() and has 2 variants discussed in this article. 1. pollFirstEntry() : It removes and retrieves a key-value pair with the least key value in the ma
4 min read
Java.util.TreeMap.floorEntry() and floorKey() in Java
Finding greatest number less than given value is used in many a places and having that feature in a map based container is always a plus. Java.util.TreeMap also offers this functionality using floor() function. There are 2 variants, both are discussed below. 1. floorEntry() : It returns a key-value mapping associated with the greatest key less than
3 min read
java.lang.Math.atan2() in Java
atan2() is an inbuilt method in Java that is used to return the theta component from the polar coordinate. The atan2() method returns a numeric value between -[Tex]\pi [/Tex]and [Tex]\pi [/Tex]representing the angle [Tex]\theta [/Tex]of a (x, y) point and the positive x-axis. It is the counterclockwise angle, measured in radian, between the positiv
1 min read
java.net.URLConnection Class in Java
URLConnection Class in Java is an abstract class that represents a connection of a resource as specified by the corresponding URL. It is imported by the java.net package. The URLConnection class is utilized for serving two different yet related purposes, Firstly it provides control on interaction with a server(especially an HTTP server) than URL cl
5 min read
Java 8 | ArrayDeque removeIf() method in Java with Examples
The removeIf() method of ArrayDeque is used to remove all those elements from ArrayDeque which satisfies a given predicate filter condition passed as a parameter to the method. This method returns true if some element are removed from the Vector. Java 8 has an important in-built functional interface which is Predicate. Predicate, or a condition che
3 min read
Java.util.GregorianCalendar Class in Java
Prerequisites : java.util.Locale, java.util.TimeZone, Calendar.get()GregorianCalendar is a concrete subclass(one which has implementation of all of its inherited members either from interface or abstract class) of a Calendar that implements the most widely used Gregorian Calendar with which we are familiar. java.util.GregorianCalendar vs java.util.
10 min read
Java lang.Long.lowestOneBit() method in Java with Examples
java.lang.Long.lowestOneBit() is a built-in method in Java which first convert the number to Binary, then it looks for first set bit present at the lowest position then it reset rest of the bits and then returns the value. In simple language, if the binary expression of a number contains a minimum of a single set bit, it returns 2^(first set bit po
3 min read
Java Swing | Translucent and shaped Window in Java
Java provides different functions by which we can control the translucency of the window or the frame. To control the opacity of the frame must not be decorated. Opacity of a frame is the measure of the translucency of the frame or component. In Java, we can create shaped windows by two ways first by using the AWTUtilities which is a part of com.su
5 min read
Practice Tags :
three90RightbarBannerImg