1. Introduction
In Java, the groupingBy collector of the Stream API is not limited to just Lists but can also be used with Sets. It allows us to group elements of a Set based on a certain property, resulting in a Map. This feature can be extremely useful in various scenarios where we need to categorize or aggregate data from a Set.
2. Program Steps
1. Create a Set of custom objects.
2. Convert the Set to a Stream and apply the Collectors.groupingBy() method to group the elements by a certain property.
3. Print the resulting Map to the console.
3. Code Program
import java.util.Set;
import java.util.HashSet;
import java.util.Map;
import java.util.stream.Collectors;
class Item {
String name;
String category;
Item(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 SetGroupingByExample {
public static void main(String[] args) {
// Step 1: Create a Set of custom objects
Set<Item> items = new HashSet<>(Set.of(
new Item("Apple", "Fruit"),
new Item("Banana", "Fruit"),
new Item("Broccoli", "Vegetable"),
new Item("Carrot", "Vegetable")
));
// Step 2: Convert the Set to a Stream and apply the Collectors.groupingBy() method
Map<String, List<Item>> itemsByCategory = items.stream()
.collect(Collectors.groupingBy(Item::getCategory));
// Step 3: Print the resulting Map to the console
System.out.println(itemsByCategory);
}
}
Output:
{Fruit=[Apple: Fruit, Banana: Fruit], Vegetable=[Carrot: Vegetable, Broccoli: Vegetable]}
4. Step By Step Explanation
Step 1: We initialize a Set of Item objects, where each Item has a name and a category.
Step 2: The Set is converted to a Stream, and the Collectors.groupingBy() method is used to group the elements by the category property. This returns a Map where the key is the category, and the value is a List of Item objects belonging to that category.
Step 3: The resulting Map is printed to the console, displaying the items grouped by their categories.