Sorting the Employees Salary in Each Department in Descending Order
Categories: Java 8(JDK1.8) Java Java Examples
package r4r.co.in.emp;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Employees {
// Sorting the Employees Salary in Each Department in Descending Order
public static void main(String[] args) {
List<Employee> empList = new ArrayList<Employee>();
empList.add(new Employee(1, "Rajesh", 41, 123, "M", "HR", "Banglore", 2020));
empList.add(new Employee(2, "Rahul", 43, 120, "M", "HR", "Hyderabad", 2015));
empList.add(new Employee(3, "Rohit", 42, 115, "M", "HR", "Chennai", 2014));
empList.add(new Employee(4, "Ranu", 45, 125, "M", "HR", "Chennai", 2013));
empList.add(new Employee(5, "Rani", 38, 150, "F", "IT", "Noida", 2013));
empList.add(new Employee(6, "Bimal", 28, 140, "M", "IT", "Lucknow", 2017));
empList.add(new Employee(7, "Juhi", 23, 130, "F", "IT", "Pune", 2016));
empList.add(new Employee(8, "Reena", 28, 145, "F", "IT", "Trivandrum", 2015));
empList.add(new Employee(9, "Meena", 32, 160, "F", "IT", "Banglore", 2010));
empList.add(new Employee(10, "Kiran", 31, 162, "F", "AC", "Delhi", 2010));
Map<String, Stream<Employee>> employeesListBySalary = empList.stream()
.collect(Collectors.groupingBy(Employee::getDeptName,
Collectors.collectingAndThen(Collectors.toList(),
list -> list.stream().sorted(Comparator.comparingDouble(Employee::getSalary).reversed()))));
employeesListBySalary.forEach((deptName, employees) -> {
System.out.println(deptName);
System.out.println(employees.collect(Collectors.toList()));
});
}
}