For inexperienced developer usually it is hard to imagine the real benefit of using Java Stream API instead of regular for/foreach cycles. Today I’ll show several examples that will help you significantly shorten your Java code.
This is our Employee class:
public class Employee {
private String name;
private int age;
private int salary;
private String position;
public Employee(String name, int age, int salary, String position) {
this.name = name;
this.age = age;
this.salary = salary;
this.position = position;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public int getSalary() {
return salary;
}
public String getPosition() {
return position;
}
}
Grouping the list of employees according to their positions (division into lists)
Map<String, List<Employee>> map1 = employees.stream()
.collect(Collectors.groupingBy(Employee::getPosition));
Grouping the list of employees according to their positions (division into sets)
Map<String, Set<Employee>> map2 = employees.stream()
.collect(Collectors.groupingBy(Employee::getPosition, Collectors.toSet()));
Counting the number of employees in a particular position
Map<String, Long> map3 = employees.stream()
.collect(Collectors.groupingBy(Employee::getPosition, Collectors.counting()));
Grouping the list of employees according to their positions, while we are only interested in names
Map<String, Set<String>> map4 = employees.stream()
.collect(Collectors.groupingBy(Employee::getPosition, Collectors.mapping(Employee::getName, Collectors.toSet())));
Calculation of the average salary for this position
Map<String, Double> map5 = employees.stream()
.collect(Collectors.groupingBy(Employee::getPosition, Collectors.averagingInt(Employee::getSalary)));
Grouping the list of employees by their position, employees are represented only by names in a single line
Map<String, String> map6 = employees.stream()
.collect(Collectors.groupingBy(Employee::getPosition,
Collectors.mapping(Employee::getName, Collectors.joining(", ", "{", "}"))));
Grouping the list of employees by their positions and by age
Map<String, Map<Integer, List<Employee>>> collect = employees.stream()
.collect(Collectors.groupingBy(Employee::getPosition, Collectors.groupingBy(Employee::getAge)));
If you know more interesting examples of using groupingBy please write them in the comments bellow.










Thank you, Joel