Lambda Expressions and Functional Interfaces

What are Lambda Expressions

Lambda Expressions are the expressions through which we can represent an Anonymous function. Anonymous functions do not have any name or modifier.

Example:- ()-> System.out.println("Lambda Example")

But to implement these methods in java classes, we need Functional Interfaces.

What are Functional Interfaces

The interface that contains only one abstract method but can have multiple default and static methods is called a functional interface.

Ex:- Runnable (run()), Callable (call()), Comparable(compareTo()), Comparator(compare()).

Custom Functional Interface

Below is a code snippet of a custom functional interface.

@FunctionalInterface
public interface MyFunctionalInterface {

    void m1();

    default void m2(){
        System.out.println("Default method-1");
    }

    default void m3(){
        System.out.println("Default method-2");
    }

    static void m4(){
        System.out.println("static method-1");
    }
}

Functional Interface with Lamda Expressions

Below is the code snippet of the calculator class with lambda expression containing subtract function

interface CalculatorSub{
    int substract(int i1,int i2);
}

public class CalculatorSubImpl {

    public static void main(String[] args) {
        CalculatorSub calsub=(i1,i2)->{
            if(i2<i1){
                throw new RuntimeException("message");
            }else{
                return i2-i1;
            }
        };

        System.out.println(calsub.substract(8,20)); //o/p:- 12
    }
}

Real-life Example of Lambda Expressions

Suppose there is a list of books and we want to sort that list on the basis of ascending order of names, then it can be done easily using the Comparator functional interface and using its lambda expression to sort it.

Below is the code snippet of same

Book.java

//Real time example to use Lambda exp
public class Book {

    private int id;
    private String name;
    private int pages;

    public Book() {
    }

    public Book(int id, String name, int pages) {
        this.id = id;
        this.name = name;
        this.pages = pages;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getPages() {
        return pages;
    }

    public void setPages(int pages) {
        this.pages = pages;
    }

    @Override
    public String toString() {
        return "Book{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", pages=" + pages +
                '}';
    }
}

BookDAO.java

import java.util.ArrayList;
import java.util.List;

public class BookDAO {

    public List<Book> getBooks(){
        List<Book> books=new ArrayList<>();
        books.add(new Book(101,"Core Java",400));
        books.add(new Book(363,"Hibernate",180));
        books.add(new Book(561,"Spring",400));
        books.add(new Book(433,"Webservice",180));
        return books;
    }
}

BookService.java

import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class BookService {

    public List<Book> getBooksInSort(){
        List<Book> books=new BookDAO().getBooks();
        //use comparator lambda to sort on the basis of name asc order.
        Collections.sort(books,(o1,o2)-> o1.getName().compareTo(o2.getName()));
        return books;
    }

    public static void main(String[] args) {
        System.out.println(new BookService().getBooksInSort());
        //o/p :- [Book{id=101, name='Core Java', pages=400}, Book{id=363, name='Hibernate', pages=180},
        // Book{id=561, name='Spring', pages=400}, Book{id=433, name='Webservice', pages=180}]
    }

}

Summary

In this post, we have learned about java lambda expressions and functional interfaces.

Thank you for reading. If you found this article helpful, react and share. Cheers.