Java Exercise
In this exercise, you will create a Java program that demonstrates the use of **Streams** and **functional operations**. First, you will create a Stream from a collection of data. Then, you will apply various functional operations to that Stream, such as filtering, mapping, and reducing, to efficiently transform and process the information. This exercise will allow you to explore how Java facilitates data manipulation using its Streams API.
Instructions:
- Create a list of integers or strings.
- Convert the list to a Stream using the
stream()
method.
- Apply functional operations such as
filter()
, map()
, and reduce()
to the Stream.
- Print the results after each operation to observe how the data is transformed.
- Demonstrate how Streams operations allow efficient collection management and parallel data processing, if necessary.
This exercise will help you understand how **functional operations** in Java allow you to manage collections more efficiently, using a declarative and expressive style, improving the clarity and performance of your application. code.
View Example Code
import java.util.*;
import java.util.stream.*;
public class Main {
public static void main(String[] args) {
// Create a list of numbers
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
// Filter the even numbers, multiply them by 2, and calculate their sum
int result = numbers.stream()
.filter(n -> n % 2 == 0) // Filter even numbers
.map(n -> n * 2) // Multiply each number by 2
.reduce(0, Integer::sum); // Reduce the list to the sum
// Display the result
System.out.println("The sum of the even numbers multiplied by 2 is: " + result);
}
}
Output:
The sum of even numbers multiplied by 2 is 60
This program uses **Streams** in Java to process a list of numbers. It first filters out the even numbers, then multiplies them by 2, and finally calculates the sum of these values using the reduce()
reduction operation. When you run the program, you can see how the data is efficiently transformed and processed using functional operations.