July 28, 2022

How to find the count of employees in each department using java 8 streams and collection | interview questions MAANG

/**
 * 
 */
package com.learning.stockmarket;

import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.stream.Collectors;

/**
 * @author vishnu prasad blog
 *
 */
public class MainClass {

/**
* @param args
*/
public static void main(String[] args) {
List<Employee> empList = addEmployee();
Map<Integer, Long> result = empList.stream().collect(Collectors.groupingBy(Employee:: getDeptId, Collectors.counting()));
System.out.println(result);
}

private static List<Employee> addEmployee() {
List<Employee> list = new ArrayList<>();
int id = 1;

for (int i = 0; i < 100; i++) {
byte[] array = new byte[7]; 
    new Random().nextBytes(array);
    String name = new String(array, Charset.forName("UTF-8"));
    
    int dept = new Random().nextInt(6);

Employee employee = new Employee(id, name, dept);
id = id++;
list.add(employee);

}

return list;
}

}

Employee


/**
 * 
 */
package com.learning.stockmarket;

/**
 * @author vishnu prasad blog

 * Kozhikode
 */
public class Employee {
private int id;
private String name;
private int deptId;
public Employee(int id, String name, int deptId) {
this.id = id;
this.name = name;
this.deptId = deptId;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getDeptId() {
return deptId;
}
public void setDeptId(int deptId) {
this.deptId = deptId;
}


}


No comments:

Post a Comment

Your feedback may help others !!!

Facebook comments