1. Introduction
In Java, the groupingBy collector is a versatile tool, typically applied to elements within a stream to group them by a certain characteristic. Interestingly, this functionality is not limited to Lists or Sets; we can also group the elements of a Map by transforming its values into a Stream and employing the Collectors.groupingBy() method. This process is particularly beneficial when there is a need to categorize Map elements based on a specific attribute, which yields a nested Map.
2. Program Steps
1. Initialize a Map containing objects.
2. Transform the Map values into a Stream.
3. Utilize the Collectors.groupingBy() method on the Stream to arrange the objects by a certain attribute.
4. Display the resulting grouped Map.
3. Code Program
import java.util.Map;
import java.util.HashMap;
import java.util.List;
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) {
// 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"));
// 2. Convert the values of the Map to a Stream.
// 3. Apply the Collectors.groupingBy() method to group the objects by their category.
Map<String, List<Product>> productsByCategory = productMap.values().stream()
.collect(Collectors.groupingBy(Product::getCategory));
// 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: A Map, named productMap, is initialized to hold Product objects, each containing a name and a category.
Step 2: The values of productMap are converted to a Stream.
Step 3: The Collectors.groupingBy() method is employed on the Stream to group the Product objects based on their category, resulting in a new Map where the key is the category, and the value is a List of Product objects belonging to that category.
Step 4: The final grouped Map is printed to the console, showcasing the products organized by their categories.