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:
- Create a list of integers.
- Use a lambda expression to filter the even numbers in the list.
- Use a lambda expression to sort the list of numbers from smallest to largest.
- 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.
View Example Code
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(5, 8, 1, 12, 3, 7, 2, 10, 4, 6);
List<Integer> evens = numbers.stream()
.filter(n -> n % 2 == 0)
.collect(Collectors.toList());
List<Integer> sorted = numbers.stream()
.sorted((a, b) -> a - b)
.collect(Collectors.toList());
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.