Java 8 - Streams Grouping By Example Code - Part 1



😀Hi Guys,

Welcome to Java Inspires,

In this post, we will see how to use grouping using streams from java 8.

Here, we will create a list of employee and then we try group by employees by they department and more.



package com.example.demo;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

public class StreamGroupByExample {

	public static void main(String[] args) {

		List<Employee> employees = new ArrayList<>();

		employees.add(new Employee(1010L, "John", 1000000, "PBB"));
		employees.add(new Employee(1011L, "Dane", 1000000, "PBB"));
		employees.add(new Employee(1012L, "Kent", 100000, "CPB"));
		employees.add(new Employee(1013L, "Albert", 100000, "CPB"));
		employees.add(new Employee(1014L, "Mike", 100000, "CPB"));

		// group by employee department
		Map<String, List<Employee>> emplByDept = employees.stream()
				.collect(Collectors.groupingBy(Employee::getDepartment));
		System.out.println(emplByDept);

		// get all department names from employees
		Set<String> depSet = employees.stream().map(e -> e.getDepartment()).collect(Collectors.toSet());

		System.out.println(depSet);

		// department wise sum of salary
		Map<String, Integer> depSal = employees.stream()
				.collect(Collectors.groupingBy(Employee::getDepartment, Collectors.summingInt(Employee::getSalary)));

		System.out.println(depSal);

	}
}

class Employee {
	private Long id;
	private String name;
	private Integer salary;
	private String department;

	public Employee() {
		super();
	}

	public Employee(Long id, String name, Integer salary, String department) {
		super();
		this.id = id;
		this.name = name;
		this.salary = salary;
		this.department = department;
	}

	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Integer getSalary() {
		return salary;
	}

	public void setSalary(Integer salary) {
		this.salary = salary;
	}

	public String getDepartment() {
		return department;
	}

	public void setDepartment(String department) {
		this.department = department;
	}

}


Post a Comment

Previous Post Next Post