17.6.5 Grouping Employees By Department

Figure 17.14 uses Stream method collect (line 95) to group Employees by department. Method collect’s argument is a Collector that specifies how to summarize the data into a useful form. In this case, we use the Collector returned by Collectors static method groupingBy, which receives a Function that classifies the objects in the stream—the values returned by this function are used as the keys in a Map. The corresponding values, by default, are Lists containing the stream elements in a given category. When method collect is used with this Collector, the result is a Map<String, List<Employee>> in which each String key is a department and each List<Employee> contains the Employees in that department. We assign ...

Get Java™ How To Program (Early Objects), Tenth Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.