Last active
November 23, 2019 06:31
-
-
Save ojitha/fefc7fec5e1df6ca7d7ce198ffab2cfe to your computer and use it in GitHub Desktop.
This example shows how to group employees by their departments. The intention of this example, to show the use of the <b>Collectors.groupingBy</b> functionality.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /* | |
| This example shows how to group employees by their departments. | |
| The intention of this example, to show the use of the <b>Collectors.groupingBy</b> | |
| functionality. | |
| */ | |
| import java.util.List; | |
| import java.util.stream.Collectors; | |
| class Dept { | |
| private int deptId; | |
| private String deptName; | |
| public Dept(int deptId, String deptName) { | |
| this.deptId = deptId; | |
| this.deptName = deptName; | |
| } | |
| public int getDeptId() { | |
| return deptId; | |
| } | |
| public String getDeptName() { | |
| return deptName; | |
| } | |
| } | |
| class Emp { | |
| private Dept dept; | |
| private String empName; | |
| public Emp(Dept dept, String empName) { | |
| this.dept = dept; | |
| this.empName = empName; | |
| } | |
| public Dept getDept() { | |
| return dept; | |
| } | |
| public String getEmpName() { | |
| return empName; | |
| } | |
| } | |
| var acc = new Dept(1,"Account"); | |
| var digital = new Dept(2,"Digital"); | |
| var marketing = new Dept(3,"Marketing"); | |
| var employees = List.of( | |
| new Emp(acc, "Acc-1"), | |
| new Emp(acc, "Acc-2"), | |
| new Emp(digital, "Digital-1"), | |
| new Emp(marketing, "m-1"), | |
| new Emp(marketing, "m-2"), | |
| new Emp(marketing, "m-3") | |
| ); | |
| // Group employees by department | |
| employees.stream() | |
| .collect(Collectors.groupingBy(Emp::getDept)) | |
| .forEach((d,l) -> System.out.println(d.getDeptName()+" => "+ | |
| l.stream() | |
| .map(Emp::getEmpName) | |
| .collect(Collectors.joining(", ")) | |
| ) | |
| ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment