java lambda expressions example

Scott 87 Published: 11/18/2024

java lambda expressions example

Here's a comprehensive example of using Java Lambda Expressions.

Lambda expressions were introduced in Java 8 as a way to simplify code and improve readability. They are anonymous functions that can be defined inline, within the context where they will be used.

Here's an example of using lambda expressions with the Stream API:

import java.util.List;

import java.util.Arrays;

import java.util.stream.Stream;

public class LambdaExample {

public static void main(String[] args) {

// Create a list of numbers

List numbers = Arrays.asList(1, 2, 3, 4, 5);

// Use lambda expression to filter even numbers and sum them up

int sum = Stream.of(numbers)

.filter(n -> n % 2 == 0) // Filter out odd numbers

.mapToInt(i -> i) // Convert stream to IntStream

.sum();

System.out.println("Sum of even numbers: " + sum);

}

}

In this example, we use the Stream API to create a stream from a list of integers. We then apply several operations to this stream:

Filtering out odd numbers using a lambda expression (n -> n % 2 == 0). This is an example of how you can use a lambda expression to define a predicate. Mapping each number in the stream to its integer value, effectively converting the stream from Stream<Integer> to IntStream. This is done using another lambda expression (i -> i). Calculating the sum of all even numbers in the original list.

By using these operations on the stream, we can simplify complex computations and make our code more expressive and easier to read.

Lambda expressions are not limited to working with streams. They can be used anywhere where a functional interface (an interface with a single abstract method) is expected. Here's an example of using lambda expressions as event listeners:

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

public class LambdaExample {

public static void main(String[] args) {

// Create a button

javax.swing.JButton button = new javax.swing.JButton("Click me");

// Add an ActionListener to the button that prints out the event source

button.addActionListener(new ActionListener() {

@Override

public void actionPerformed(ActionEvent e) {

System.out.println("Button clicked: " + button);

}

});

// Alternative: Use a lambda expression instead of implementing an interface

button.addActionListener(e -> System.out.println("Button clicked: " + button));

}

}

In this example, we use a lambda expression to define an ActionListener that will be called when the button is clicked. This can simplify our code and make it more expressive.

Lambda expressions are powerful tools in Java that allow us to write concise, readable, and efficient code. They have many applications beyond just stream processing or event listeners, but these examples should give you a good idea of how they can be used effectively.

How to create a Java lambda function?

Java Lambda Expressions are used to implement functional programming concepts like map, filter, and reduce. They were first introduced in Java 8. Here's how you can create one:

The syntax for creating a Java lambda expression is as follows:

(Arguments) -> { Code }

The Arguments part is optional if you have no parameters.

Let's say we have an ArrayList of integers and we want to square each number using a lambda function. Here's how you can do it:

import java.util.*;

import java.util.function.*;

public class Main {

public static void main(String[] args) {

ArrayList numbers = new ArrayList<>();

numbers.add(1);

numbers.add(2);

numbers.add(3);

// Lambda function to square each number

numbers.stream()

.map(num -> num * num)

.forEach(System.out::println);

}

}

In this code:

We create an ArrayList called numbers. We use the stream() method to convert the ArrayList into a Stream. The map() function applies our lambda expression (in this case, num -> num * num) to each element in the Stream. It's like saying "For each number in the list, square it". Finally, we use the forEach() function to print out the squared numbers.

The output would be:

1

4

9

You can also have multiple parameters in your lambda function:

(numbers.stream()

.map((num1, num2) -> num1 + num2)

.forEach(System.out::println));

In this case, you're summing each pair of numbers in the list.

If you want to ignore some of the parameters in your lambda function and use only some of them, you can do that like so:

(numbers.stream()

.filter((num1, num2) -> Math.abs(num1 - num2) < 10)

.forEach(System.out::println));

Here, we're creating a filter to ignore all pairs of numbers where the absolute difference between them is greater than or equal to 10.