DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
View Events Video Library
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Integrating PostgreSQL Databases with ANF: Join this workshop to learn how to create a PostgreSQL server using Instaclustr’s managed service

Mobile Database Essentials: Assess data needs, storage requirements, and more when leveraging databases for cloud and edge applications.

Monitoring and Observability for LLMs: Datadog and Google Cloud discuss how to achieve optimal AI model performance.

Automated Testing: The latest on architecture, TDD, and the benefits of AI and low-code tools.

Related

  • Projections/DTOs in Spring Data R2DBC
  • Functional Interfaces in Java
  • Functional Interface Explained in Detail Introduced From Java 8
  • Smart Dependency Injection With Spring: Assignability (Part 2 of 3)

Trending

  • An Introduction to Build Servers and Continuous Integration
  • Exploring the Evolution and Impact of Computer Networks
  • Build a Digital Collectibles Portal Using Flow and Cadence (Part 1)
  • No Spark Streaming, No Problem
  1. DZone
  2. Coding
  3. Java
  4. Lambda Expressions in Java 8

Lambda Expressions in Java 8

Still having some trouble grasping Java 8's new lambda expressions? You aren't alone. This article will help you see how to get your lambda expressions up and running.

Shivshankar Pal user avatar by
Shivshankar Pal
·
Updated Jan. 02, 18 · Tutorial
Like (60)
Save
Tweet
Share
56.03K Views

Join the DZone community and get the full member experience.

Join For Free

Let's start with lambda expressions. What are they? And how do they work?

I Googled lots of posts and YouTube videos before now to understand lambda expressions, but I found it difficult to understand because I haven't used any functional language before. So I decided to write a blog post to help people like me.

Don't worry about the name. It's the same old Java programming with a bit of a different flavor. It just reduces the words required to write a function or call a function or write an anonymous class.

Take a look at some lambda expression syntax:

Syntax:

1. (int a, int b) -> {  return a + b; }  

     1. Function with two parameters.

     2. (a,b) -> {  return a + b; } works the same.


2. () -> System.out.println("Hello World");  

     1. Function without parameter.                      

3. (String s) -> { System.out.println(s); }  

     1. Function with one parameter.

4. (s)->System.out.println(s);  

     1. No need to specify the type of parameter.

     2. No need for curly braces for single statements.

5. () -> 42  

6. () -> { return 3.1415 };  

I am sure some programmers will try to write a "hello world" program using lambda expression syntax after checking out the syntax, like so:

class Test()
{
    public static void main(String[] args)
    {
        ()->System.out.println(“Hello world”);
    }
}

I don't know about you guys, but I did it. And found this: "we can use lambda expressions only with Functional interfaces."

Q.  Now what is a functional interface and why is it important for lambda expressions?

Functional interface: A functional interface is an interface with a single abstract method.

Example:

public interface FunctionalInterface
{
    public void show();
} 

As you can see the above interface has only one method, so it is a functional interface.

Now try to write the program “hello world”.

Here is an old method before lambda expressions:

public class TestFunInter {
    public static void main(String[] args) {
        FunctionalInterface f = new FunctionalInterface() {
            public void show() {
                System.out.println("hello world");
            }
        };
        f.show();
    }
}
Output:
hello world

And

public class TestFunInter
{
    public static void main(String[] args)
    {
        new FunctionalInterface() {
            @Override
            public void show()
            {
                System.out.println("hello world");
            }
        }.show();
    }
}
Output:
hello world

Now check it out in the lambda way:

public class TestFunInter {
    public static void main(String[] args){
        FunctionalInterface f=()->System.out.println("hello world");
        f.show();
    }
}
Output:
hello world

Now compare all the ways of writing same code—you can get the proper idea of what the lambda is doing for you. Now some of you have started imagining and might by now be asking a question like “Why does it need a functional interface to work?".

This means whenever we want to do anything using lambda expressions we need to create a functional interface first.

API developers have already provided many Functional interfaces needed for general use. And these interfaces are located in the package java.util.function. You can check out this link for further details.

Let's check out the java.util.function package.

Example:

import java.util.function.*;

public class Test{
    public static void main(String[] args){
        BiConsumer<String, String> bi = (a, b) -> System.out.println(a + b);
        bi.accept("shiv ", "----------");
    }
}
Output:
-shiv----------

You can see in above example:

  1. import -> we have imported function package.

  2. In the main method we have created a reference variable of type interface with two generic types.

  3. This interface has one abstract method which accepts two parameters. and returns nothing. You can check details here.

Lambda Expression With Threads

Note: We all know that a “Runnable” interface has only one method “run()”. So it is also a “Functional interface” and can be used with a lambda expression.

Example 1: Use of thread type 1:

public class TestClass {
    public static void main(String[] args) {
        Runnable r = new Runnable() {
            public void run() {
                System.out.println("I am runnable thread");
            }
        };
        Thread t = new Thread(r);
        t.start();
    }
}

Let's do the same using a lambda expression:

public class TestClass {
    public static void main(String[] args){
        Runnable r = () -> System.out.println("lambda expression");
        Thread t = new Thread(r);
        t.start();
    }
}

Example 2: Use of thread type 2:

public class TestClass {
    public static void main(String[] args){
        new Thread(new Runnable(){
            public void run(){
                System.out.println("thread");
            }
        }).start();
    }
}

The same with lambda expressions:

public class TestClass {
    public static void main(String[] args){
        new Thread(()->System.out.println("lambda thread")).start();
    }
}

Just compare the standard and lambda ways, and you can find the things lambda made easier.

What lambda expression can do for us is:

  1. Can define anonymous functions

  2. Can be assigned to a variable

  3. Can be passed to functions

  4. Can be returned from functions

Interface (computing) Java (programming language)

Published at DZone with permission of Shivshankar Pal. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Projections/DTOs in Spring Data R2DBC
  • Functional Interfaces in Java
  • Functional Interface Explained in Detail Introduced From Java 8
  • Smart Dependency Injection With Spring: Assignability (Part 2 of 3)

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: