A common operation that you have become familiar with in SQL is the GROUP BY statement which is used in conjunction with the aggregate functions such as count. It might look something like this:
In java 8 the idea of grouping objects in a collection based on the values of one or more of their properties is simplified by using a Collector. A collector is another new interface introduced in Java 8 for defining how to perform a reduction operation on a stream and with the functional nature allows you to achieve a grouping with a single statment. It might even spark debates with your DBA for control or their lack of understanding. Should it happen in code or in the database? In the example below, we will peform a number of group by statements to show the simplicity and flexibility of the interface.
Setup
Group by teacher name
This example will show how to "group classes by a teacher's name". Here you will pass the groupingBy method a function in the form of a method reference extracting each teacher name to the corresponding StudentClass which will return 1 key to many elements. This is similar to guava's Multimap collection which allows for easy mapping of a single key to multiple values.
Output
Group by class level
Similar to above, this example will show "show all classes by level".
Output
groupBy aggregate
This example will "count the number of classes per level". In sql, it might look like this:
In an overloaded groupingBy method, you can pass a second collector. Collectors have various reduce operations which can be passed, in this case Collectors.counting which will count the number of classes in each level.