What is a lambda expression in Java?

Frederica 151 Published: 07/12/2024

What is a lambda expression in Java?

I'll respond in English as requested!

A lambda expression in Java is a special kind of anonymous function that can be defined inline within your code. It's a shorthand way to define small, one-off functions that don't need their own class or method declaration.

A lambda expression typically consists of three parts:

The parameter list (if any): This specifies the input parameters for the lambda function. The arrow token (->): This separates the parameter list from the lambda body. The lambda body: This is the code that will be executed when the lambda is invoked.

Here's a simple example:

(String s) -> System.out.println(s)

This lambda expression takes a single String parameter s, and when called, prints its value to the console using System.out.println().

Lambdas can also take multiple parameters by separating them with commas:

(int x, int y) -> x + y

In this case, the lambda takes two int parameters x and y, and returns their sum when called.

One of the main use cases for lambdas is as a replacement for inner classes or anonymous classes. Prior to Java 8, if you needed a small, one-off function, you'd typically define an entire new class just for that purpose. With lambda expressions, you can achieve similar functionality with much less code and effort.

Java 8 also introduced method references, which allow you to create lambdas even more concisely:

String::toUpperCase

This creates a lambda that takes no parameters (i.e., an empty parameter list) and returns the upper-case equivalent of its input using the toUpperCase() method.

When choosing between a traditional class-based approach versus a lambda expression, consider the following:

Use lambdas for small, one-off functions that don't need their own class. Use classes if you need more complex functionality, or if you'll be reusing the function elsewhere in your code.

In summary, Java's lambda expressions provide a concise and expressive way to define small, one-off functions inline within your code. They're an essential tool for simplifying and streamlining your Java programming experience!

Java lambda expressions examples

Here are some examples of using Java lambda expressions:

Basic Example:
List names = Arrays.asList("John", "Alice", "Bob");

names.replaceAll(s -> s.toUpperCase());

System.out.println(names);

// Output: [JOHN, ALICE, BOB]

In this example, we create a list of strings and use the replaceAll method to replace each string with its uppercase version. The lambda expression s -> s.toUpperCase() takes a string as input and returns its uppercase version.

Filtering a Collection:
List words = Arrays.asList("hello", "world", "java", "lambda");

List filteredWords = words.stream()

.filter(word -> word.length() > 4)

.collect(Collectors.toList());

System.out.println(filteredWords);

// Output: [hello, java]

In this example, we create a list of strings and use the stream method to create a stream from the collection. We then use the filter method to filter out any words that have fewer than 5 characters. The lambda expression word -> word.length() > 4 takes a string as input and returns a boolean indicating whether the length is greater than 4.

Mapping a Collection:
List numbers = Arrays.asList("1", "2", "3", "4");

List squaredNumbers = numbers.stream()

.map(s -> Integer.parseInt(s) * s.length())

.collect(Collectors.toList());

System.out.println(squaredNumbers);

// Output: [1, 4, 9, 16]

In this example, we create a list of strings and use the stream method to create a stream from the collection. We then use the map method to transform each string into an integer by parsing the string as an integer and multiplying it by its length. The lambda expression s -> Integer.parseInt(s) * s.length() takes a string as input and returns an integer.

Reducing a Collection:
List numbers = Arrays.asList("1", "2", "3", "4");

Integer sum = numbers.stream()

.mapToInt(Integer::parseInt)

.sum();

System.out.println(sum);

// Output: 10

In this example, we create a list of strings and use the stream method to create a stream from the collection. We then use the mapToInt method to transform each string into an integer by parsing the string as an integer, and the sum method to calculate the sum of all integers.

Handling Multiple Arguments:
List points = Arrays.asList("1,2", "3,4", "5,6");

List<int[]> coordinates = points.stream()

.map(p -> {

String[] parts = p.split(",");

return new int[]{Integer.parseInt(parts[0]), Integer.parseInt(parts[1])};

})

.collect(Collectors.toList());

System.out.println(coordinates);

// Output: [[1, 2], [3, 4], [5, 6]]

In this example, we create a list of strings representing coordinates (x,y) and use the stream method to create a stream from the collection. We then use the map method to transform each string into an array of integers by splitting the string into two parts using the comma as a separator, parsing each part as an integer, and creating a new array with the results. The lambda expression takes two strings as input (x and y) and returns an array of integers.

These are just a few examples of how Java lambda expressions can be used to simplify code and improve readability. Lambda expressions can be used in a variety of contexts, including stream processing, event handling, and data transformation.