1. Introduction

In Java, the map() and reduce() functions, available through the Stream API, offer a powerful and expressive way of processing elements in a Set. The map() function applies a given function to each element, while the reduce() function combines the elements into a single value. In this post, we will showcase how to use the map() and reduce() functions to process elements in a Set.

2. Program Steps

1. Create and initialize a Set of integers.

2. Print the original Set to the console.

3. Convert the Set into a Stream using the stream() method.

4. Apply the map() function to multiply each element of the Stream by 2.

5. Utilize the reduce() function to calculate the product of the elements in the modified Stream.

6. Print the result to the console.

3. Code Program

import java.util.HashSet;
import java.util.Optional;
import java.util.Set;

public class MapReduceSet {

    public static void main(String[] args) {

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

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

        // Step 3: Convert the Set into a Stream
        // Step 4: Apply the map() function to double each element
        // Step 5: Apply the reduce() function to calculate the product of the elements
        Optional<Integer> product = numbers.stream()
                                           .map(n -> n * 2)
                                           .reduce((n1, n2) -> n1 * n2);

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

Output:

Original Set: [1, 2, 3, 4, 5]
Product of doubled elements: 3840

4. Step By Step Explanation

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

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

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

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

Step 5: The reduce() function is used with a lambda expression (n1, n2) -> n1 * n2 to calculate the product of the doubled elements, producing a single Optional<Integer> result product.

Step 6: The isPresent() method is used to check if product has a value. If it does, the value is retrieved using the get() method and printed to the console as Product of doubled elements: 3840. Otherwise, an error message is printed.