Streams and Functional Operations

In this exercise, you will learn how to work with **Streams** and **functional operations** in Java. Using the Streams API, you will perform operations such as filtering, mapping, and data reduction, allowing you to write cleaner, more efficient, and expressive code. This exercise will help you understand how to leverage advanced Java features to handle collections more effectively and efficiently.

Topic

Functional Programming and Lambda Expressions

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:

  1. Create a list of integers or strings.
  2. Convert the list to a Stream using the stream() method.
  3. Apply functional operations such as filter(), map(), and reduce() to the Stream.
  4. Print the results after each operation to observe how the data is transformed.
  5. 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.


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.


 Share this JAVA exercise