Course contentsShow
← Java
Lesson 1570 of 2,87034. Collectors in DepthFree lesson

Grouping with Method References

Use method references as classifier functions for cleaner groupingBy expressions.

Grouping with Method References

You'll learn: How to use method references instead of lambdas to make your groupingBy collectors cleaner and more readable.

In the previous lesson, you saw how to use lambda expressions as classifier functions in groupingBy. When your classifier simply calls a single method on each element, you can use a method reference instead—making your code shorter and clearer.

Why Method References?

When you write groupingBy(person -> person.getCity()), you're creating a lambda that does nothing but call one method. Java lets you replace this pattern with a method reference: groupingBy(Person::getCity).

Think of it like giving directions. Instead of saying "take each person, then call their getCity method," you simply say "use the getCity method." The meaning is identical, but the second version is more direct.

Syntax Comparison

With lambda:

Map<String, List<Employee>> byDepartment = 
    employees.stream()
             .collect(Collectors.groupingBy(emp -> emp.getDepartment()));

With method reference:

Map<String, List<Employee>> byDepartment = 
    employees.stream()
             .collect(Collectors.groupingBy(Employee::getDepartment));

Both produce exactly the same result, but the method reference version is cleaner and easier to read at a glance.

When to Use Method References

Use method references when your classifier function is a simple getter or single method call. If you need any additional logic (like transforming the value or combining fields), stick with a lambda expression.

Key Takeaway: Method references (ClassName::methodName) make groupingBy classifiers cleaner when you're simply calling a single method on each element, reducing boilerplate and improving readability.