1. Introduction

Java’s Stream API, introduced in Java 8, brings a new abstraction of data manipulation using a functional approach. The map(), reduce() methods are part of the Stream API and provide powerful tools for processing elements in collections, particularly maps. In this tutorial, we will explore how to use map() and reduce() methods to perform operations on the values of a Map in Java.

2. Program Steps

1. Create and initialize a Map of Integer keys and values.

2. Print the original Map to the console.

3. Convert the values of the Map into a Stream using the values().stream() method.

4. Apply the map() function to square each value in the Stream.

5. Use the reduce() method to sum up the squared values.

6. Print the result to the console.

3. Code Program

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

public class MapReduceMap {

    public static void main(String[] args) {

        // Step 1: Create and initialize a Map of Integer keys and values
        Map<Integer, Integer> numberMap = new HashMap<>();
        numberMap.put(1, 2);
        numberMap.put(2, 3);
        numberMap.put(3, 4);

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

        // Step 3: Convert the values of the Map into a Stream
        // Step 4: Apply the map() function to square each value
        // Step 5: Use the reduce() method to sum up the squared values
        Optional<Integer> sumOfSquares = numberMap.values().stream()
                                                  .map(x -> x * x)
                                                  .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 Map: {1=2, 2=3, 3=4}
Sum of squares: 29

4. Step By Step Explanation

Step 1: A Map of Integer keys and values named numberMap is created and initialized with key-value pairs.

Step 2: The original Map numberMap is printed to the console.

Step 3: The values().stream() method is used to convert the values of the Map numberMap into a Stream.

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

Step 5: The reduce() function is used with a method reference Integer::sum to calculate the sum of the squared values, 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: 29. Otherwise, an error message is printed.