Skip to main content
Published on

Lambda in Java

Share:

Introduction

Lambda expressions, introduced in Java 8, revolutionised the way we write and understand code in Java, making it more concise, readable, and expressive.

What is Lambda?

Lambda is a concept that allows you to represent an instance of a functional interface in a shorter and more simplified way. Basically, it is a way to write anonymous functions: functions without a name.

Advantages of Lambda

  1. Conciseness: The code becomes leaner and cleaner.
  2. Readability: It makes reading and understanding the code easier.
  3. Flexibility: It can be used together with new features from Java 8, such as Streams.

Usage Example

package com.caffeinealgorithm.programaremjava;

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

public class Lambda {
  private List<String> people = new ArrayList<>();

  public void Run() {
    people.add("Nelson Silva");
    people.add("Larissa Fernandes");
    people.add("Pedro Henrique");
    people.add("Raquel Soares");

    // listPeople();

    people.forEach((person) -> System.out.printf("Name: %s\n", person));
  }

  private void listPeople() {
    for (String person : people)
      System.out.printf("Name: %s\n", person);
  }
}

/*
  Name: Nelson Silva
  Name: Larissa Fernandes
  Name: Pedro Henrique
  Name: Raquel Soares
*/

How Does It Work?

In the example shown above, we see the use of lambda to iterate over a list and print each element. Here, the forEach method accepts a lambda expression, which defines what to do with each element in the list.

More Examples

  1. Sort a list:
List<Integer> numbers = Arrays.asList(5, 2, 8, 3, 1);
numbers.sort((n1, n2) -> n1.compareTo(n2));
System.out.println(numbers);
  1. Create a thread:
new Thread(() -> System.out.println("Thread being executed using Lambda!")).start();
  1. Operations with Streams:
long count = people.stream()
                .filter(person -> person.startsWith("N"))
                .count();
System.out.println("Number of people whose name starts with the letter N: " + count);

Conclusion

Lambda expressions are a powerful addition to the Java language, allowing developers to write code in a more efficient and expressive way. Furthermore, lambdas are crucial for taking full advantage of Java's new features, especially those introduced in Java 8, such as Streams.

Happy coding!