Skip to main content

Lambda Expression Java

How to use Lambda Expression Java

In this article, we are going to see how we can use Lambda Expression Java. We will see how lambda expressions make our code so much easy to write and read. It helps to remove unnecessary coding from our program. Basically, Lambda expression makes our code more focused towards what to do not how to do.

What is Lambda Expression Java

A Lambda Expression can be considered as a brief description of a method or function without a name. A method or function in java has name, parameters or arguments, return type and body Similarly a lambda expression in java also consists of arguments, body and return type but without the name.
Let's have a first look of lambda expression in java:
// First look of Lambda expression in java
(Book book) -> {
 return book.getTitle().contains("Java");
Also, look at equivalent method or function representation in java:
boolean check(Book book) {
 return book.getTitle().contains("Java");
Don't think about the syntax of lambda expression now, we will discuss this later, but we can see in case of lambda expression we just need to write what we need to Also we don't need to write a name for the lambda expression as compared to in case of the method definition.

Functional Interface

Before we are going to see how lambda expression works in java, first we should understand what is a Functional Interface. A Functional interface is an interface that contains only one method declaration. For example:
interface BookConstraint{
  boolean check(Book book);
Runnable, Comparator all are the functional interfaces.
After java 8, a functional interface can be instantiated using lambda expression java or In other words, a lambda expression can only be written for a functional interface. Let's have a look
BookConstraint constraintByLambdaExpression =  (Book book) -> {
 return book.getTitle().contains("Java");
Here we can say lambda expression is equivalent to Anonymous Class or lambda expression java is the replacement of anonymous inner classes, the Anonymous Class is an inner class and it is a way to provide definition to an interface or class anonymously before lambda expressions in java 8.
 * Similar representation of lambda expression in java in terms of Anonymous Class.
 * As we can see how much unnecessary code we need to write.
BookConstraint constraintByAnonymousClass = new BookConstraint() {
     public boolean check(Book book) {
         return book.getTitle().contains("Java");
How to use the above written lambda expression:
Book book = new Book("Learn Java");
boolean isJavaBook = constraintByLambdaExpression.check(book);
   System.out.println("This is a Java Book");

Lambda Expression Java Syntax

The lambda expression is the combination of arguments, an arrow sign (->) and lambda body.
Syntax of lambda expression java
(arguments) -> { 
   lambda body i.e., One or more statements;
Arguments : These are the arguments of the lambda expression. It can be zero or more. The sequence and type of arguments must be match with the one and only method declare in the Functional Interface.
Arrow : This is the arrow used to separate the arguments from the lambda body.
Lambda Body : This is the body of lambda. Basically it becomes the method definition of the one and only Functional interface's method.

Few Example of Lambda Expression Java

(String str) -> { 
   return str.toUpperCase();
(String str1, String str2) -> { 
   return str1.concat(str2);
(Book book) -> { 
   return book.getTitle().contains("Java");
() -> { 
   return new Book();
// Also, this lambda not returning anything i.e., it returns void
(Book book, String title) -> { 
   title = title.toUpperCase();

Single Line : Lambda Expression Java

A lambda expression can be written in a single line when there is only one statement in the lambda body like all the examples mentioned earlier in this post.
Syntax of single statement lambda expression java
(arguments) -> expression;
NOTE : When we are writing single line lambda expression curly braces '{' , '}' and return keyword is not used.
For example, what it will look like for our BookConstraint Interface mentioned earlier in this post
BookConstraint constraint = (Book book) -> book.getTitle().contains("Java");
One more thing, we can remove the argument type mention in the lambda expression because java knows the lambda expression is for which Functional Interface. So Java automatically detects the type of the arguments according to the sequence declared in the method of Functional Interface. So finally, the code will look like:
BookConstraint constraint = book -> book.getTitle().contains("Java");

Few More Example of Single Line Lambda Expression Java

str -> str.toUpperCase();
(str1 ,str2) -> str1.concat(str2);
() -> new Book();

Behavior Parameterization using Lambda Expression Java

Behavior Parameterization is a programming pattern in which we pass the behavior of a program from outside the program to parameterize the behavior. Let see how:
Suppose you have a list of the book with you and you need to write two functionalities is One that returns all java books and another that will return all book having price under Rs. 500/-.
A simple approach is to write two methods like:
List<Book> filterJavaBook(List<Book> books){
    List<Book> javaBooks = new ArrayList<>();
    for (Book book : books) {
       if(book.getTitle().contains("Java")) {
    return javaBooks;
List<Book> filterPriceUnder500Book(List<Book> books){
    List<Book> priceUnder500Books = new ArrayList<>();
    for (Book book : books) {
       if(book.getPrice() <= 500) {
    return priceUnder500Books;
This approach is simple but what happens if we need to write 5 or 10 or more than 10 functionalities, then we need to write n number of method which make our code very verbose and hard to maintain. To handle this situation we can parameterize the behavior. Let see how
For Behavior Parameterization, first we need to create an interface that works as an abstraction for behavior in the method
interface BookConstraint{
  boolean check(Book book);
This interface works as the behavior of the functionality within the method and the behavior is provided from outside the method as the argument.
List<Book> filterBooks(List<Book> books , BookConstraint bookConstraint){
    List<Book> filteredBooks = new ArrayList<>();
    for(Book book : books) {
        if(bookConstraint.check(book)) {
    return filteredBooks;
Now we can create n number of behavior for the function and pass the behavior as an argument. To write the definition of the behavior we can use either lambda expression or anonymous classes but we know which one is better and easy to write.
List javaBooks = filterBooks(listOfAllBooks , book -> book.getTitle().contains("Java"));
List priceUnder500Books = filterBooks(listOfAllBooks, book -> book.getPrice() <= 500);

So this is all about lambda expression java, how to use that, where to use that, how lambda expression is better than anonymous class how we can make our code very neat and clean. Also, we learn how to use lambda expression in java to achieve behavior parameterization in java.


Popular posts from this blog

How HashMap works internally in java

How Hashmap works Internally in Java In this article, we are going to see how HashMap internally works in java. Also, we will have a look at what Java 8 made changes on the internal working of Hashmap to make it faster. What is Hashmap and Hashing in java? How Hashmap works Internally in Java is majorly dependent upon the Hashing Principle. So, Before going to learn how HashMap works internally in java, lets first understand what is HashMap and hashing. HashMap : A HashMap is a map used to store mappings of key-value pairs. Also, it works on the Principle of Hashing. To know more about the HashMap, visit this article: HashMap in Java Hashing Principle : Simply, Hashing is a method used to produce an integer value from an object and this integer value known as the hash value. In HashMap, the key object is used for Hashing.
Internal Struture of the HashMap in java For internal working of HashMap, HashMap maintains an array of bucket, each bucket is a linked-list and linked list is a li…

HashMap in Java

HashMap in Java In this article, we are going to learn about the most important class of Java known as HashMap. HashMap in java is the most used map interface and it is used in our regular or day-to-day programming practices.
What is HashMap in java? Lets first start with basic definition of HashMap,
HashMap is a map which store key-value pair, where each key is mapped with a value.
HashMap defined in java.util package and implements map interface which provides functionalities to perform basic operation like store, retrieve, size of the map etc. It is a part of Java Collection Framework. Time complexity of HashMap in Java? : Time complexity to store and retrieve data from the HashMap is O(1) in the Best Case. But it can be O(n) in the worst case and after the changes made in Java 8 the worst case time complexity can be O(log n) atmost. Internal working of HashMap in java HashMap maintains an array of the buckets, where each bucket is a linked-list and the linked list is a list of…

ArrayList in Java

ArrayList in Java In this article, we are going to discuss ArrayList in Java. ArrayList is a class from the Java Collection Framework and widely in our programs. We use ArrayList as a substitute for the array. So, it is important to know ArrayList in detail. We are going to see what is ArrayList in Java, how we can create the instance of ArrayList and the methods provided by the ArrayList in Java.

If you already familiar to ArrayList, you may learn common programs related to ArrayList.
Table of ContentsWhat is ArrayList in Java?Hierarchy of the ArrayList in java?How to create objects of ArrayList in Java?How to create an ArrayList of Custom Objects?How to iterate ArrayList in Java?How to get the elements by index from ArrayList in Java?How to check whether an elements is stored in the ArrayList in Java?How to remove elements from the ArrayList in Java?Few more methods of ArrayList in Java?
What is ArrayList in Java? ArrayList in Java is a List in which we can store and retrieve elemen…