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

Table of Contents

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.

Was this post helpful?


import_contacts

You may also like:

Related Posts

  • Unable to obtain LocalDateTime from TemporalAccessor
    20 February

    [Fixed] Unable to obtain LocalDateTime from TemporalAccessor

    Table of ContentsUnable to obtain LocalDateTime from TemporalAccessor : ReasonUnable to obtain LocalDateTime from TemporalAccessor : FixLocalDate’s parse() method with atStartOfDay()Use LocalDate instead of LocalDateTimeWas this post helpful? In this article, we will see how to fix Unable to obtain LocalDateTime from TemporalAccessor in Java 8. Unable to obtain LocalDateTime from TemporalAccessor : Reason You […]

  • Java LocalDate to Instant
    17 February

    Convert LocalDate to Instant in Java

    Table of ContentsJava LocalDate to InstantUsing toInstant() wth ZoneIdUsing toInstant() with ZoneOffsetWas this post helpful? In this article, we will see how to convert LocalDate to Instant in Java. Java LocalDate to Instant Instant class provides an instantaneous point in time. When you want to convert LocalDate to Instant, you need to provide time zone. […]

  • Java Instant to LocalDate
    17 February

    Convert Instant to LocalDate in Java

    Table of ContentsUsing ofInstant method [ Java 9+]Using ZoneDateTime’s toLocalDate() [Java 8]Was this post helpful? In this article, we will see how to convert Instant to LocalDate in java. Using ofInstant method [ Java 9+] Java 9 has introduced static method ofInstant() method in LocalDate class. It takes Instant and ZoneId as input and returns […]

  • Convert String to LocalDateTime in Java
    17 February

    Convert String to LocalDateTime in Java

    Table of ContentsJava String to LocalDateTimeConvert String to LocalDateTime with custom formatWas this post helpful? In this article, we will see how to convert String to LocalDateTime in Java. LocalDateTime class was introduced in Java 8. LocalDateTime represents local date and time without timezone information. It is represented in ISO 8601 format (yyyy-MM-ddTHH:mm:ss) by default. […]

  • Java LocalDateTIme to String
    16 February

    Format LocalDateTime to String in Java

    Table of ContentsJava LocalDateTime To StringConvert LocalDateTime to Time Zone ISO8601 StringParse String to LocalDateTimeWas this post helpful? In this article, we will see how to format LocalDateTime to String in java. Java LocalDateTime To String To format LocalDateTime to String, we can create DateTimeFormatter and pass it to LocalDateTime’s format() method. [crayon-62b6da2c0e38e518237827/] Here are […]

  • 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()ConclusionWas this post helpful? 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, […]

Comments

Leave a Reply

Your email address will not be published.

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.