Java 8 – Solving Real Time Queries Using Java 8 Features – Employee Management System


Index Page : Link

Donate : Link

Medium Blog : Link

Applications : Link

  • Let’s try to solve some of the real time queries faced in the Employee Management System using Java 8 features.
  • We will be using following Employee class and employeeList as example while solving the queries.

1. Employee class:

class Employee {
	int id;
	String name;
	int age;
	String gender;
	String department;
	int yearOfJoining;
	double salary;

	public Employee(int id, String name, int age, String gender, String department, int yearOfJoining, double salary) {
		this.id = id;
		this.name = name;
		this.age = age;
		this.gender = gender;
		this.department = department;
		this.yearOfJoining = yearOfJoining;
		this.salary = salary;
	}

	public int getId() {
		return id;
	}

	public String getName() {
		return name;
	}

	public int getAge() {
		return age;
	}

	public String getGender() {
		return gender;
	}

	public String getDepartment() {
		return department;
	}

	public int getYearOfJoining() {
		return yearOfJoining;
	}

	public double getSalary() {
		return salary;
	}

	@Override
	public String toString() {
		return "Id : " + id + ", Name : " + name + ", age : " + age + ", Gender : " + gender + ", Department : "
				+ department + ", Year Of Joining : " + yearOfJoining + ", Salary : " + salary;
	}
}

2. List Of Employees : employeeList

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

employeeList.add(new Employee(111, "Jiya Brein", 32, "Female", "HR", 2011, 25000.0));
employeeList.add(new Employee(122, "Kaushal Jani", 25, "Male", "Sales And Marketing", 2015, 13500.0));
employeeList.add(new Employee(133, "Harshil Nagar", 29, "Male", "Infrastructure", 2012, 18000.0));
employeeList.add(new Employee(144, "Raj Darbar", 28, "Male", "Product Development", 2014, 32500.0));
employeeList.add(new Employee(155, "Nima Roy", 27, "Female", "HR", 2013, 22700.0));
employeeList.add(new Employee(166, "Sid Barot", 43, "Male", "Security And Transport", 2016, 10500.0));
employeeList.add(new Employee(177, "Pruthvi Soni", 35, "Male", "Account And Finance", 2010, 27000.0));
employeeList.add(new Employee(188, "Parth Dabgar", 31, "Male", "Product Development", 2015, 34500.0));
employeeList.add(new Employee(199, "Amelia Zoe", 24, "Female", "Sales And Marketing", 2016, 11500.0));
employeeList.add(new Employee(200, "Ashish Patel", 38, "Male", "Security And Transport", 2015, 11000.5));
employeeList.add(new Employee(211, "Jasna Kaur", 27, "Female", "Infrastructure", 2014, 15700.0));
employeeList.add(new Employee(222, "Aaalap Patel", 25, "Male", "Product Development", 2016, 28200.0));
employeeList.add(new Employee(233, "Jyothi Reddy", 27, "Female", "Account And Finance", 2013, 21300.0));
employeeList.add(new Employee(244, "Divyesh Solanki", 24, "Male", "Sales And Marketing", 2017, 10700.5));
employeeList.add(new Employee(255, "Jay Solanki", 23, "Male", "Infrastructure", 2018, 12700.0));
employeeList.add(new Employee(266, "Sanvi Pandey", 26, "Female", "Product Development", 2015, 28900.0));
employeeList.add(new Employee(277, "Kishan Panchal", 31, "Male", "Product Development", 2012, 35700.0));

3. Real Time Queries On employeeList

3.1 How many male and female employees are there in the organization?
3.2 Print the name of all departments in the organization?
3.3 What is the average age of male and female employees?
3.4 Get the details of highest paid employee in the organization?
3.5 Get the names of all employees who have joined after 2015?
3.6 Count the number of employees in each department?
3.7 What is the average salary of each department?
3.8 Get the details of youngest male employee in the product development department?
3.9 Who has the most working experience in the organization?
3.10 How many male and female employees are there in the sales and marketing team?
3.11 What is the average salary of male and female employees?
3.12 List down the names of all employees in each department?
3.13 What is the average salary and total salary of the whole organization?
3.14 Separate the employees who are younger or equal to 25 years from those employees who are older than 25 years.
3.15 Who is the oldest employee in the organization? What is his age and which department he belongs to?

3.1 How many male and female employees are there in the organization?

For queries such as above where you need to group the input elements, use the Collectors.groupingBy() method. In this query, we use Collectors.groupingBy() method which takes two arguments. We pass Employee::getGender as first argument which groups the input elements based on gender and Collectors.counting() as second argument which counts the number of entries in each group.

Map<String, Long> noOfMaleAndFemaleEmployees = employeeList.stream()
		.collect(Collectors.groupingBy(Employee::getGender, Collectors.counting()));

System.out.println(noOfMaleAndFemaleEmployees);

Output:

{Male=11, Female=6}

3.2 Print the name of all departments in the organization?

Use distinct() method after calling map(Employee::getDepartment) on the stream. It will return unique departments.

employeeList.stream()
	.map(Employee::getDepartment)
	.distinct()
	.forEach(System.out::println);

Output:

HR
Sales And Marketing
Infrastructure
Product Development
Security And Transport
Account And Finance

3.3 What is the average age of male and female employees?

Use same method as query 3.1 but pass Collectors.averagingInt(Employee::getAge) as the second argument to Collectors.groupingBy().

Map<String, Double> avgAgeOfMaleAndFemaleEmployees=
		employeeList.stream().collect(Collectors.groupingBy(Employee::getGender, Collectors.averagingInt(Employee::getAge)));

System.out.println(avgAgeOfMaleAndFemaleEmployees);

Output:

{Male=30.181818181818183, Female=27.166666666666668}

3.4 Get the details of highest paid employee in the organization?

Optional<Employee> optional = employeeList.stream()
	.max((e1, e2) -> Double.compare(e1.getSalary(), e2.getSalary()));
System.out.println(optional.get());

Optional<Employee> highestPaidEmployeeWrapper = employeeList.stream()
	.collect(Collectors.maxBy(Comparator.comparingDouble(Employee::getSalary)));
System.out.println(highestPaidEmployeeWrapper.get());

Output:

Id : 277, Name : Kishan Panchal, age : 31, Gender : Male, Department : Product Development, Year Of Joining : 2012, Salary : 35700.0
Id : 277, Name : Kishan Panchal, age : 31, Gender : Male, Department : Product Development, Year Of Joining : 2012, Salary : 35700.0

3.5 Get the names of all employees who have joined after 2015?

For such queries which require filtering of input elements, use Stream.filter() method which filters input elements according to supplied Predicate.

employeeList.stream()
	.filter(e -> e.getYearOfJoining() > 2015)
	.map(Employee::getName)
	.forEach(System.out::println);

Output:

Sid Barot
Amelia Zoe
Aaalap Patel
Divyesh Solanki
Jay Solanki

3.6 Count the number of employees in each department?

Map<String, Long> employeeCountByDepartment = employeeList.stream()
	.collect(Collectors.groupingBy(Employee::getDepartment, Collectors.counting()));

Set<Entry<String, Long>> entrySet = employeeCountByDepartment.entrySet();

for (Entry<String, Long> entry : entrySet) {
    System.out.println(entry.getKey()+" : "+entry.getValue());
}

Output:

Product Development : 5
Security And Transport : 2
Sales And Marketing : 3
Infrastructure : 3
HR : 2
Account And Finance : 2

3.7 What is the average salary of each department?

Map<String, Double> employeeCountByDepartment = employeeList.stream()
	.collect(Collectors.groupingBy(Employee::getDepartment, Collectors.averagingDouble(Employee::getSalary)));

Set<Entry<String, Double>> entrySet = employeeCountByDepartment.entrySet();

for (Entry<String, Double> entry : entrySet) {
    System.out.println(entry.getKey()+" : "+entry.getValue());
}

Output:

Product Development : 31960.0
Security And Transport : 10750.25
Sales And Marketing : 11900.166666666666
Infrastructure : 15466.666666666666
HR : 23850.0
Account And Finance : 24150.0

3.8 Get the details of youngest male employee in the product development department?

Optional<Employee> youngestMaleEmployeeInProductDevelopmentWrapper = employeeList.stream()
	.filter(e -> e.getGender().equals("Male") && e.getDepartment().equals("Product Development"))
	.min((e1, e2) -> e1.getAge() - e2.getAge());
System.out.println(youngestMaleEmployeeInProductDevelopmentWrapper.get());

Output:

Id : 222, Name : Aaalap Patel, age : 25, Gender : Male, Department : Product Development, Year Of Joining : 2016, Salary : 28200.0

3.9 Who has the most working experience in the organization?

Optional<Employee> seniorMostEmployeeWrapper = employeeList.stream()
	.sorted(Comparator.comparingInt(Employee::getYearOfJoining)).findFirst();
System.out.println(seniorMostEmployeeWrapper.get());

seniorMostEmployeeWrapper = employeeList.stream()
	.sorted((e1, e2) -> e1.getYearOfJoining() - e2.getYearOfJoining()).findFirst();
System.out.println(seniorMostEmployeeWrapper.get());

seniorMostEmployeeWrapper = employeeList.stream()
	.min(Comparator.comparingInt(Employee::getYearOfJoining));
System.out.println(seniorMostEmployeeWrapper.get());

seniorMostEmployeeWrapper = employeeList.stream()
	.min((e1, e2) -> e1.getYearOfJoining() - e2.getYearOfJoining());
System.out.println(seniorMostEmployeeWrapper.get());

Output:

Id : 177, Name : Pruthvi Soni, age : 35, Gender : Male, Department : Account And Finance, Year Of Joining : 2010, Salary : 27000.0
Id : 177, Name : Pruthvi Soni, age : 35, Gender : Male, Department : Account And Finance, Year Of Joining : 2010, Salary : 27000.0
Id : 177, Name : Pruthvi Soni, age : 35, Gender : Male, Department : Account And Finance, Year Of Joining : 2010, Salary : 27000.0
Id : 177, Name : Pruthvi Soni, age : 35, Gender : Male, Department : Account And Finance, Year Of Joining : 2010, Salary : 27000.0

3.10 How many male and female employees are there in the sales and marketing team?

Map<String, Long> countMaleFemaleEmployeesInSalesMarketing = employeeList.stream()
	.filter(e -> e.getDepartment() == "Sales And Marketing")
	.collect(Collectors.groupingBy(Employee::getGender, Collectors.counting()));
System.out.println(countMaleFemaleEmployeesInSalesMarketing);

Output:

{Female=1, Male=2}

3.11 What is the average salary of male and female employees?

Map<String, Double> avgSalaryOfMaleAndFemaleEmployees = employeeList.stream()
	.collect(Collectors.groupingBy(Employee::getGender, Collectors.averagingDouble(Employee::getSalary)));
System.out.println(avgSalaryOfMaleAndFemaleEmployees);

Output:

{Male=21300.090909090908, Female=20850.0}

3.12 List down the names of all employees in each department?

Map<String, List<Employee>> employeeListByDepartment = employeeList.stream()
	.collect(Collectors.groupingBy(Employee::getDepartment));

Set<Entry<String, List<Employee>>> entrySet = employeeListByDepartment.entrySet();

for(Entry<String, List<Employee>> entry : entrySet) {
	System.out.println("Employee in: " + entry.getKey());
	for(Employee employee : entry.getValue()) {
		System.out.println(employee.getName());
	}
	System.out.println();
}

Output:

Employee in: Product Development
Raj Darbar
Parth Dabgar
Aaalap Patel
Sanvi Pandey
Kishan Panchal

Employee in: Security And Transport
Sid Barot
Ashish Patel

Employee in: Sales And Marketing
Kaushal Jani
Amelia Zoe
Divyesh Solanki

Employee in: Infrastructure
Harshil Nagar
Jasna Kaur
Jay Solanki

Employee in: HR
Jiya Brein
Nima Roy

Employee in: Account And Finance
Pruthvi Soni
Jyothi Reddy

3.13 What is the average salary and total salary of the whole organization?

For this query, we use Collectors.summarizingDouble() on Employee::getSalary which will return statistics of the employee salary like max, min, average and total.

DoubleSummaryStatistics employeeSalaryStatistics = employeeList.stream()
	.collect(Collectors.summarizingDouble(Employee::getSalary));

System.out.println("Average Salary: " + employeeSalaryStatistics.getAverage());
System.out.println("Total Salary: " + employeeSalaryStatistics.getSum());

Output:

Average Salary: 21141.235294117647
Total Salary: 359401.0

3.14 Separate the employees who are younger or equal to 25 years from those employees who are older than 25 years.

For this query, we will be using Collectors.partitioningBy() method which separates input elements based on supplied Predicate.

Map<Boolean, List<Employee>> partitionEmployeesByAge = employeeList.stream()
	.collect(Collectors.partitioningBy(e -> e.getAge() > 25));

Set<Entry<Boolean, List<Employee>>> entrySet = partitionEmployeesByAge.entrySet();
for (Entry<Boolean, List<Employee>> entry : entrySet) {
	if (entry.getKey()) {
        System.out.println("Employees older than 25 years :");
    } else {
        System.out.println("Employees younger than or equal to 25 years :");
    }
	List<Employee> list = entry.getValue();
    for (Employee e : list) 
    {
        System.out.println(e.getName());
    }
    System.out.println();
}

Output:

Employees younger than or equal to 25 years :
Kaushal Jani
Amelia Zoe
Aaalap Patel
Divyesh Solanki
Jay Solanki

Employees older than 25 years :
Jiya Brein
Harshil Nagar
Raj Darbar
Nima Roy
Sid Barot
Pruthvi Soni
Parth Dabgar
Ashish Patel
Jasna Kaur
Jyothi Reddy
Sanvi Pandey
Kishan Panchal

3.15 Who is the oldest employee in the organization? What is his age and which department he belongs to?

Optional<Employee> oldestEmployeeWrapper = employeeList.stream()
	.sorted((e1, e2) -> e2.getAge() - e1.getAge()).findAny();
System.out.println(oldestEmployeeWrapper.get());

oldestEmployeeWrapper = employeeList.stream()
	.max((e1, e2) -> e1.getAge() - e2.getAge());
System.out.println(oldestEmployeeWrapper.get());

Output:

Id : 166, Name : Sid Barot, age : 43, Gender : Male, Department : Security And Transport, Year Of Joining : 2016, Salary : 10500.0
Id : 166, Name : Sid Barot, age : 43, Gender : Male, Department : Security And Transport, Year Of Joining : 2016, Salary : 10500.0

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s