Home >Java >javaTutorial >What Is a Lambda Function in Java and Example.

What Is a Lambda Function in Java and Example.

Linda Hamilton
Linda HamiltonOriginal
2024-09-20 06:41:31336browse

What Is a Lambda Function in Java and Example.

1. Understanding Lambda Functions

Lambda functions, or lambda expressions, are a way to provide clear and concise syntax for writing anonymous methods in Java. They enable you to write implementations of functional interfaces in a more readable and expressive manner.

1.1 What Is a Lambda Function?

A lambda function in Java is a short block of code that takes in parameters and returns a value. It is essentially a method without a name, allowing you to pass functionality as an argument to methods or store it as a variable.

Syntax

The basic syntax of a lambda function is as follows:

(parameters) -> expression

Or, if you have multiple statements:

(parameters) -> {
    // multiple statements
}

1.2 Functional Interfaces

To use lambda expressions, you need a functional interface. A functional interface is an interface that has exactly one abstract method. Examples include Runnable, Callable, and custom interfaces with a single abstract method.

1.3 Benefits of Lambda Functions

  • Conciseness : Lambda expressions help reduce boilerplate code.
  • Readability : They make the code more readable and expressive.
  • Ease of Use : Useful in scenarios like stream operations and event handling.

2. Using Lambda Functions in Java

2.1 Basic Example

Let's start with a simple example of a lambda function in Java. We'll use a Runnable interface to demonstrate:

public class LambdaExample {
    public static void main(String[] args) {
        // Traditional way
        Runnable oldRunnable = new Runnable() {
            @Override
            public void run() {
                System.out.println("Running in a thread!");
            }
        };
        new Thread(oldRunnable).start();

        // Using Lambda Expression
        Runnable lambdaRunnable = () -> System.out.println("Running in a thread with Lambda!");
        new Thread(lambdaRunnable).start();
    }
}

Output

Running in a thread!
Running in a thread with Lambda!

2.2 Advanced Example: Using Lambda with Collections

Lambda functions are particularly useful when working with collections. Here's an example that demonstrates sorting a list of strings using lambda expressions:

import java.util.Arrays;
import java.util.List;

public class LambdaListExample {
    public static void main(String[] args) {
        List<String> names = Arrays.asList("John", "Jane", "Paul", "Alice");

        // Using lambda to sort the list
        names.sort((name1, name2) -> name1.compareTo(name2));

        // Printing sorted names
        names.forEach(name -> System.out.println(name));
    }
}

Output

Alice
Jane
John
Paul

2.3 Practical Demo: Filtering with Streams

Lambda expressions shine when combined with Java Streams for operations like filtering and mapping. Here’s how you can use lambdas to filter and process a list of integers:

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class LambdaStreamExample {
    public static void main(String[] args) {
        List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);

        // Filtering even numbers and squaring them
        List<Integer> squaredEvens = numbers.stream()
            .filter(n -> n % 2 == 0)
            .map(n -> n * n)
            .collect(Collectors.toList());

        // Printing the result
        squaredEvens.forEach(System.out::println);
    }
}

Output

4
16
36
64
100

3. Conclusion

Lambda functions in Java offer a more compact and expressive way to handle anonymous methods and functional interfaces. They can greatly simplify your code and improve its readability, especially when dealing with collections and stream operations.

If you have any questions or need further clarification, feel free to leave a comment below!

Read posts more at : What Is a Lambda Function in Java and Example.

The above is the detailed content of What Is a Lambda Function in Java and Example.. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn