Java Stream groupingBy() Tutorial 🎯

beginner
10 min

Java Stream groupingBy() Tutorial 🎯

Welcome to our comprehensive guide on the groupingBy() method in Java Stream API! This tutorial is designed for both beginners and intermediate learners. By the end of this lesson, you'll understand how to group elements in a Stream based on certain criteria, making your code more efficient and effective.

What is Java Stream? 📝

Before diving into groupingBy(), let's quickly recap what Stream is. In Java 8, Stream is a sequence of elements that supports parallel aggregate operations. It allows us to perform operations like filtering, sorting, and mapping on collections without modifying the original data.

Understanding groupingBy() 💡

The groupingBy() method is used to group the elements in a Stream based on a specified function. This function takes an element and returns a key that defines the group.

Prerequisites ✅

To fully grasp the concept of groupingBy(), you should be familiar with:

  1. Java basics
  2. Lambda expressions
  3. Java Stream API (check out our Java Stream tutorial if you're not familiar with it)

Getting Started with groupingBy() 🎯

Let's start with a simple example. Suppose we have a list of products with their categories, and we want to group these products based on their categories.

java
import java.util.stream.*; import java.util.*; List<Product> products = Arrays.asList( new Product("Apple", "Fruits"), new Product("Banana", "Fruits"), new Product("Orange", "Fruits"), new Product("Laptop", "Electronics"), new Product("Mobile", "Electronics") );

Here's a Product class for our example:

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

Now, let's use groupingBy() to group the products based on their categories:

java
products.stream() .collect(Collectors.groupingBy(product -> product.getCategory()));

This will return a Map<String, List<Product>> where the keys are categories, and the values are lists of products belonging to those categories.

groupingBy() with Collectors.collectingAndThen() 💡

You can apply additional operations on the grouped data using Collectors.collectingAndThen(). Let's count the number of products in each category:

java
products.stream() .collect(Collectors.groupingBy(product -> product.getCategory(), Collectors.collectingAndThen( Collectors.counting(), count -> count + " Products" ) ))

This will return a Map<String, String> where the keys are categories, and the values are the number of products in those categories, followed by the word "Products".

Advanced Example 🎯

Let's consider a more complex scenario. Suppose we have a list of employees, and we want to group them based on their departments and salaries.

java
import java.util.stream.*; import java.util.*; class Employee { String name; String department; double salary; public Employee(String name, String department, double salary) { this.name = name; this.department = department; this.salary = salary; } } List<Employee> employees = Arrays.asList( new Employee("John", "IT", 60000), new Employee("Mike", "HR", 50000), new Employee("Sarah", "IT", 70000), new Employee("Emily", "Finance", 55000), new Employee("Robert", "IT", 65000) );

Now, let's group the employees based on their departments and salaries, and count the number of employees in each group:

java
employees.stream() .collect(Collectors.groupingBy( employee -> employee.department + ":" + String.valueOf(employee.salary), Collectors.counting() ))

This will return a Map<String, Long> where the keys are department and salary combinations, and the values are the number of employees in those groups.

Quiz 📝

Quick Quiz
Question 1 of 1

What does the `groupingBy()` method in Java Stream API do?

That's it for our Java Stream groupingBy() tutorial! Practice these examples and try to create your own use cases to master this powerful feature of Java Stream API. Happy coding! 🎉