Lambda Expressions in Java 8

Java 8 Lambda expressions
Java 8 has introduced a new feature called Lambda expressions. It is considered to be a major change in java. As this change will bring functional programming into Java. Other languages such as Scala already have this feature so this is not new to programming world, it is new to java
Before understanding Lambda expressions, Lets first understand Functional Interface.

What is Functional Interface?

Functional interfaces are those interfaces that have only one abstract method in it. It can have more than one default or static method and can override the method from java.lang.object. Let’s create a functional interface:
Java can itself identify Functional Interface but you can also denote interface as Functional Interface by annotating it with @FunctionalInterface.
Some popular Functional Interfaces are:

Why Lambda Expressions?

Lets understand with help of  Anonymous Comparator:

Let’s say you need to sort list of movies by movie name.
Movie.java

Code to sort list of movies by name using comparator

The problem with Anonymous Comparator is of syntax. Each time you want to sort the list using a comparator, you have to remember the bulky syntax.
So generally the main problem with Anonymous classes is syntax. For very simple operation, we need to write complex code. To solve this problem, JDK has introduced a new feature called Lambda Expressions. I will take this example after explaining lambda expression to understand, how lambda expression will reduce this complex code.

What is Lambda Expressions:

lambda expression represents an anonymous function. It comprises of a set of parameters, a lambda operator (->) and a function body . You can call it function without name,
The connection between Lambda Expression and Functional Interface:
You might be thinking I have introduced the functional Interface above but how it is connected to Lambda. So Lambda expression can be applied for the abstract method of functional Interface which is being implemented or being instantiated anonymously.

Structure of Lambda Expressions

(Argument List) ->{expression;} or
(Argument List) ->{statements;}
So we can divide structure of Lambda expression to three parts:
  1. Argument list or parameters
    • Lambda expression can have zero or more arguments.
      ()->{System.out.println(“Hello”)}; //Without argument, will print hello
      (int a)->{System.out.println(a)}; // One argument, will print value of a
      (int a,int b)-> {a+b};//two argument, will return sum of these two integers
    • You can choose to not declare the type of arguments as it can be inferred from context.
    • (a,b)->{a+b}; // two argument, will return sum of these two numbers
    • you can not declare one argument’s type and do not declare type for other argument.
    • (int a,b)->{a+b}; // Compilation error
    • When there is a single parameter, if its type is inferred, it is not mandatory to use parentheses
      a->{System.out.println(a)}; // Will print value of number a
  2. Array token (->)
  3. Body
    • Body can have expression or statements.
    • If there is only one statement in body,curly brace is not needed and return type of the anonymous function is same as of body expression
    • If there are more than one statements, then it should be in curly braces and return type of anonymous function is same as value return from code block, void if nothing is returned.
Let’s take some examples ,  you want to initialize thread and now you will realize, how can lambda expression make your coding easy :
Let’s take another example of Comparator which we have seen in Anonymous Comparator in java. We will create list of movies and sort it by movie name using trivial way and lambda expressions.
Create a class called Movie.java
Create a main class called ComparatorMain.java
Output:

Before Sort by name :
Movie Name: Inception|| Movie duration: 110
Movie Name: GodFather|| Movie duration: 200
Movie Name: Forest Gump|| Movie duration: 130
Movie Name: Avengers|| Movie duration: 150
After Sort by name:
Movie Name: Avengers|| Movie duration: 150
Movie Name: Forest Gump|| Movie duration: 130
Movie Name: GodFather|| Movie duration: 200
Movie Name: Inception|| Movie duration: 110
As you can see here, we have used lambda expression for using Comparator. So in spite of writing Anonymous comparator, our expression became very easy.
So we have passed 2 arguments o1 and o2, we didn’t pass type because it can be inferred from context.
We have only one statement here, so no need to put it in curly braces.

HelloWorld Lambda Expression Example

Create an Interface Called HelloWorld
Create a class called HelloWorldMain
Run above program you will get the following output:
Hello using Lambda Expression
Hope you understand Lambda expression now, in next post, we will see more examples of it.

import_contacts

You may also like:

Related Posts

  • Find duplicate elements in the Stream
    17 October

    Java 8 – Find duplicate elements in Stream

    Table of ContentsIntroductionUsing distinct()Using Collections.frequency()Using Collectors.toSet()Using Collectors.toMap()Using Collectors.groupingBy()Conclusion Introduction When working with a collection of elements in Java, it is very common to have duplicate elements, and Java provides different APIs that we can use to solve the problem. Java 8 Stream provides the functionality to perform aggregate operations on a collection, and one of […]

  • Format Instant to String in java
    02 May

    How to format Instant to String in java

    Learn about how to format Instant to String in java.

  • Convert Date to LocalDate in java
    12 January

    Java Date to LocalDate

    Table of ContentsUsing toInstant() method of Date classUsing toInstant() method of Date classUsing java.sql.Date In this post, we will see how to convert Date to LocalDate in java. Sometimes, we may need to convert Date to new Java 8 APIs and vice versa. There are multiple ways to convert Date to LocalDate in java. Read […]

  • Convert LocalDate to Date in java
    11 January

    Java LocalDate to Date

    Table of ContentsUsing Instant objectUsing java.sql.Date In this post, we will see how to convert LocalDate to Date. Java 8 has introduced a lot of new APIs for Date and time. There can be many ways to convert Java LocalDateTime to date. Using Instant object You can convert LocalDate to Date using Instant object which […]

  • Convert Stream to List in java
    31 December

    Java Stream to List

    Table of ContentsUsing Collectors.toList()Using Collectors.toCollection()Using foreachFilter Stream and convert to ListConvert infinite Stream to List In this post, we will see how to convert Stream to List in java. There are multiple ways to convert Stream to List in java. Using Collectors.toList() You can pass Collectors.toList() to Stream.collect() method to convert Stream to List in […]

  • Convert LocalDateTime to Timestamp in java
    18 November

    Convert LocalDateTime to Timestamp in Java

    Table of ContentsLocalDateTimeTimestampConvert LocalDateTime to Timestamp In this post, we will how to convert LocalDateTime to Timestamp . Before learning how to convert localdatetime to timestamp, let us learn about LocalDateTime and Timestamp, and understand the importance of this conversion. LocalDateTime LocalDateTime was introcuded in Java 8. LocalDateTime can be imported time package: import java.time.LocalDateTime; […]

Comments

Leave a Reply

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

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.