1. Introduction

In Java, the stream() method, along with the map() and reduce() functions, can be used to perform complex operations on List objects. The map() function is used to transform each element of the list, and the reduce() function is used to produce a single result from the transformed elements. This post will illustrate how to use map() and reduce() functions on a List in Java.

2. Program Steps

1. Create and initialize a List of integers.

2. Print the original List to the console.

3. Use the stream() method to convert the List into a Stream.

4. Apply the map() function to square each element of the Stream.

5. Apply the reduce() function to sum up the squared elements, which gives a single result.

6. Print the result to the console.

3. Code Program

import java.util.Arrays;
import java.util.List;
import java.util.Optional;

public class MapReduceList {

    public static void main(String[] args) {

        // Step 1: Create and initialize a List of integers
        List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);

        // Step 2: Print the original List
        System.out.println("Original List: " + numbers);

        // Step 3: Convert the List into a Stream
        // Step 4: Apply the map() function to square each element
        // Step 5: Apply the reduce() function to sum up the squared elements
        Optional<Integer> sumOfSquares = numbers.stream()
                                                .map(n -> n * n)
                                                .reduce(Integer::sum);

        // Step 6: Print the result to the console
        if (sumOfSquares.isPresent()) {
            System.out.println("Sum of Squares: " + sumOfSquares.get());
        } else {
            System.out.println("Could not calculate the Sum of Squares");
        }
    }
}

Output:

Original List: [1, 2, 3, 4, 5]
Sum of Squares: 55

4. Step By Step Explanation

Step 1: A List of integers named numbers is created and initialized with the values 1 through 5.

Step 2: The original List numbers is printed to the console.

Step 3: The stream() method is used to convert the List numbers into a Stream.

Step 4: The map() function is applied to square each element of the Stream.

Step 5: The reduce() function is applied to sum up the squared elements, producing a single Optional<Integer> result sumOfSquares.

Step 6: The isPresent() method is used to check if sumOfSquares has a value. If it does, the value is retrieved using the get() method and printed to the console as Sum of Squares: 55. Otherwise, an error message is printed.