1. Introduction

In Java, utilizing the groupingBy functionality is not restricted to Lists or Sets. We can also apply it to a Map by converting the Map values to a Stream and then using the Collectors.groupingBy() method. This is particularly handy when you have a Map of objects and you want to group them by a specific attribute, resulting in a nested Map.

2. Program Steps

1. Initialize a Map with objects as values.

2. Convert the values of the Map to a Stream.

3. Apply the Collectors.groupingBy() method to group the objects by a specific attribute.

4. Print the resultant grouped Map.

3. Code Program

import java.util.Map;
import java.util.HashMap;
import java.util.stream.Collectors;

class Product {
    String name;
    String category;

    Product(String name, String category) {
        this.name = name;
        this.category = category;
    }

    public String getName() {
        return name;
    }

    public String getCategory() {
        return category;
    }

    @Override
    public String toString() {
        return name + ": " + category;
    }
}

public class MapGroupingByExample {

    public static void main(String[] args) {
        // Step 1: Initialize a Map with objects as values
        Map<Integer, Product> productMap = new HashMap<>();
        productMap.put(1, new Product("Laptop", "Electronics"));
        productMap.put(2, new Product("Apple", "Fruits"));
        productMap.put(3, new Product("Monitor", "Electronics"));

        // Step 2 and 3: Convert the values of the Map to a Stream and apply the Collectors.groupingBy() method
        Map<String, List<Product>> productsByCategory = productMap.values().stream()
                .collect(Collectors.groupingBy(Product::getCategory));

        // Step 4: Print the resultant grouped Map
        System.out.println(productsByCategory);
    }
}

Output:

{Fruits=[Apple: Fruits], Electronics=[Laptop: Electronics, Monitor: Electronics]}

4. Step By Step Explanation

Step 1: We create a Map called productMap that holds integers as keys and Product objects as values. Each Product has a name and a category.

Step 2 and 3: We convert the values of the productMap to a Stream and use the Collectors.groupingBy() method to group the Product objects by their category. The result is a Map where the key is the category and the value is a List of Product objects belonging to that category.

Step 4: The resulting Map, which shows products grouped by their categories, is printed to the console.