How to Write Lambda Functions in Java: A Step-by-Step Guide with Examples and Advantages


Let's say we have an ArrayList of integers, and we want to find all the even numbers in the list. Here's how you could do it without using lambda expressions:


List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
List<Integer> evenNumbers = new ArrayList<>();

for (int number : numbers) {
    if (number % 2 == 0) {
        evenNumbers.add(number);
    }
}

System.out.println("Even numbers: " + evenNumbers);

This code creates a new ArrayList called evenNumbers and loops through the numbers list, checking each number to see if it's even. If it is, the number is added to the evenNumbers list. Finally, the evenNumbers list is printed to the console.

Now let's see how we can simplify this code using lambda expressions. Instead of using a for loop, we can use the filter() method from the Stream API, which was also introduced in Java 8. Here's how the code would look with lambda expressions:


List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
List<Integer> evenNumbers = numbers.stream()
                                    .filter(number -> number % 2 == 0)
                                    .collect(Collectors.toList());

System.out.println("Even numbers: " + evenNumbers);

This code does the same thing as the previous code, but it's much shorter and easier to read. Instead of looping through the numbers list, we create a stream of integers using the stream() method. We then use the filter() method to filter out all the odd numbers, using a lambda expression to specify the condition (number % 2 == 0). Finally, we collect the even numbers into a new ArrayList using the collect() method.

I hope this example helps to illustrate how lambda expressions can simplify your code and make it easier to read and understand!

No comments:

Post a Comment