Lambda Expressions

In this exercise, you will learn how to use **Lambda Expressions** in Java, a powerful feature of functional programming that allows you to work with functions more concisely. Lambda Expressions are especially useful for working with collections and performing operations such as filtering, sorting, and data transformation in an efficient and readable manner. This exercise will guide you through practical examples to understand their use and apply lambdas in your own Java programs.

Topic

Functional Programming and Lambda Expressions

Java Exercise

In this exercise, you will create a Java program that uses Lambda Expressions to perform operations on collections. First, you will define a list of integers and then use a lambda expression to filter out even numbers. Next, you will apply another lambda expression to sort the numbers in ascending order. Finally, you'll print the results to demonstrate how Lambda Expressions allow you to perform these tasks in a more concise and functional way.

Instructions:

  1. Create a list of integers.
  2. Use a lambda expression to filter the even numbers in the list.
  3. Use a lambda expression to sort the list of numbers from smallest to largest.
  4. Print the filtered and sorted list to display the result.

This exercise will help you understand how Lambda Expressions can simplify code and improve readability when working with collections in Java, applying functional programming principles.


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

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

        // Filter even numbers using a lambda expression
        List<Integer> evens = numbers.stream()
                                     .filter(n -> n % 2 == 0)
                                     .collect(Collectors.toList());

        // Sort the list of numbers in ascending order using a lambda expression
        List<Integer> sorted = numbers.stream()
                                     .sorted((a, b) -> a - b)
                                     .collect(Collectors.toList());

        // Print the results
        System.out.println("Even numbers: " + evens);
        System.out.println("Sorted numbers: " + sorted);
    }
}

 Output:

Even numbers: [8, 12, 2, 10, 4, 6]
Ordered numbers: [1, 2, 3, 4, 5, 6, 7, 8, 10, 12]

This program demonstrates how to use **Lambda Expressions** in Java to perform operations on a collection of numbers. The lambda expression is used to filter out even numbers from the list and also to sort the list in ascending order. Lambda Expressions allow you to write more compact and readable code, taking advantage of functional programming features.


 Share this JAVA exercise