Java Exercise
In this exercise, you will create a Java program that uses Lambda Expressions and Streams to perform operations on collections. First, you will create a list of integers and then apply various transformations using Streams, such as filtering, mapping, and reducing. You will then implement Lambda Expressions to simplify the implementation of the operations. This exercise will help you understand how to apply functional programming in Java and take advantage of its benefits in terms of code conciseness and clarity.
Instructions:
- Create a list of integers using
ArrayList
.
- Use a **Stream** to filter out list elements that are greater than a given value.
- Apply a mapping operation to the list elements, converting them to their squared value.
- Use a **lambda expression** to implement a method that calculates the sum of all the elements in the list.
- Demonstrate how these operations combine to perform functional processing on a collection.
This exercise will help you understand how functional programming in Java allows you to write more concise, clear, and efficient code by leveraging the power of **Lambda Expressions** and Streams to perform complex operations more simply.
View Example Code
// Import necessary classes
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
// Create a list of integers
List<Integer> numbers = new ArrayList<>();
numbers.add(5);
numbers.add(10);
numbers.add(15);
numbers.add(20);
numbers.add(25);
// Filter numbers greater than 10
List<Integer> greaterThanTen = numbers.stream()
.filter(n -> n > 10)
.collect(Collectors.toList());
// Map numbers to get their square
List<Integer> squares = numbers.stream()
.map(n -> n * n)
.collect(Collectors.toList());
// Sum the numbers using Lambda Expressions
int sum = numbers.stream()
.reduce(0, (a, b) -> a + b);
// Print results
System.out.println("Numbers greater than 10: " + greaterThanTen);
System.out.println("Squares of the numbers: " + squares);
System.out.println("Sum of the numbers: " + sum);
}
}
Output:
Numbers greater than 10: [15, 20, 25]
Squares of numbers: [25, 100, 225, 400, 625]
Sum of numbers: 75
This program demonstrates how to use **functional programming** in Java to work with collections. A **Stream** is used to filter out numbers greater than 10, numbers are mapped to obtain their squares, and a **lambda expression** is used to calculate the total sum of the numbers in the list. When you run the program, you can see how collections are processed efficiently and concisely.