BeginnersBook

  • Home
  • Java
    • Java OOPs
    • Java Collections
    • Java Examples
  • C
    • C Examples
  • C++
    • C++ Examples
  • DBMS
  • Computer Network
  • Python
    • Python Examples
  • More…
    • jQuery
    • Kotlin
    • WordPress
    • SEO
    • JSON
    • JSP
    • JSTL
    • Servlet
    • MongoDB
    • XML
    • Perl

Java Functional Interfaces

By Chaitanya Singh | Filed Under: java

An interface with only single abstract method is called functional interface. You can either use the predefined functional interface provided by Java or create your own functional interface and use it. You can check the predefined functional interfaces here: predefined functional interfaces they all have only one abstract method. That is the reason,they are also known as Single Abstract Method interfaces (SAM Interfaces).

To use lambda expression in Java, you need to either create your own functional interface or use the pre defined functional interface provided by Java. While creating your own functional interface, mark it with @FunctionalInterface annotation, this annotation is introduced in Java 8. Although its optional, you should use it so that you get a compilation error if the interface you marked with this annotation is not following the rules of functional interfaces.

What are the rules of defining a functional interface?

The functional interface should have Only one abstract method. Along with the one abstract method, they can have any number of default and static methods.

Example 1: Creating your own functional interface

@FunctionalInterface
interface MyFunctionalInterface {

    public int addMethod(int a, int b);
}
public class BeginnersBookClass {

   public static void main(String args[]) {
        // lambda expression
    	MyFunctionalInterface sum = (a, b) -> a + b;
        System.out.println("Result: "+sum.addMethod(12, 100));
    }
}

Output:

Result: 112

Example 2: Using predefined functional interface

import java.util.function.IntBinaryOperator;

public class BeginnersBookClass {

   public static void main(String args[]) {
        // lambda expression
        IntBinaryOperator sum = (a, b) -> a + b;
        System.out.println("Result: " + sum.applyAsInt(12, 100));

    }
}

Output:

Result: 112

Functional interface example: using anonymous inner class vs using lambda expression

We have been using functional interfaces even prior to java8, they were used by creating anonymous inner classes using these interfaces. You must have seen functional interfaces such as Runnable, ActionListener, Comparator etc. They all have single abstract method. Lets see an example of ActionListener to see how it was used with Anonymous inner class and how it can be implemented using lambda expression.
ActionListener Example: Before Java 8: Using anonymous inner class

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class Example extends JFrame
{
    JButton button;
    public Example()
    {
	setTitle("Button Action Example without Lambda Expression");
	setSize(400,300);
	setVisible(true);
	setLayout(new FlowLayout());
	setDefaultCloseOperation(EXIT_ON_CLOSE);

	button = new JButton("Button");
	button.setBounds(100,100,90,40);
	button.addActionListener(new ActionListener(){  
	   public void actionPerformed(ActionEvent e){  
		System.out.println("You clicked the button."); 
	   }  
			
	});
	add(button);
    }
    public static void main(String args[])
    {
	new Example();
    }   
}

ActionListener Example: Lambda Expression

import javax.swing.*;
import java.awt.*;
class Example extends JFrame
{
    JButton button;
    public Example()
    {
	setTitle("Button Action Example using Lambda Expression");
	setSize(400,300);
	setVisible(true);
	setLayout(new FlowLayout());
	setDefaultCloseOperation(EXIT_ON_CLOSE);

	button = new JButton("Button");
	button.setBounds(100,100,90,40);
	//Lambda expression
	button.addActionListener(e-> 
	   System.out.println("You clicked the button.")); 
	
	add(button);
    }
    public static void main(String args[])
    {
	new Example();
    }   
}
❮ PreviousNext ❯

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Java Tutorial

Java Introduction

  • Java Index
  • Java Introduction
  • History of Java
  • Features of Java
  • C++ vs Java
  • JDK vs JRE vs JVM
  • JVM - Java Virtual Machine
  • First Java Program
  • Variables
  • Data Types
  • Operators

Java Flow Control

  • Java If-else
  • Java Switch-Case
  • Java For loop
  • Java while loop
  • Java do-while loop
  • Continue statement
  • break statement

Java Arrays

  • Java Arrays

OOPs Concepts

  • OOPs Concepts
  • Constructor
  • Java String
  • Static keyword
  • Inheritance
  • Types of inheritance
  • Aggregation
  • Association
  • Super Keyword
  • Method overloading
  • Method overriding
  • Overloading vs Overriding
  • Polymorphism
  • Types of polymorphism
  • Static and dynamic binding
  • Abstract class and methods
  • Interface
  • Abstract class vs interface
  • Encapsulation
  • Packages
  • Access modifiers
  • Garbage Collection
  • Inner classes
  • Static import
  • Static constructor

Java Exception Handling

  • Exception handling
  • Java try-catch
  • Java throw
  • Java throws
  • Checked and Unchecked Exceptions
  • Jav try catch finally
  • Exception Examples
  • Exception Propagation

Collections Framework

  • Collections in Java
  • Java ArrayList
  • Java LinkedList
  • Java Vector
  • Java HashSet
  • Java LinkedHashSet
  • Java TreeSet
  • Java HashMap
  • Java TreeMap
  • Java LinkedHashMap
  • Java Queue
  • Java PriorityQueue
  • Java Deque
  • Comparable interface
  • Comparator interface
  • Collections Interview Questions

MORE ...

  • Java Scanner Class
  • Java 8 Features
  • Java 9 Features
  • Java Conversion
  • Java Date
  • Java Multithreading
  • Java I/O
  • Java Serialization
  • Java Regex
  • Java AWT
  • Java Swing
  • Java Enum
  • Java Annotations
  • Java main method
  • Java Interview Q

Copyright © 2012 – 2022 BeginnersBook . Privacy Policy . Sitemap