Sorting the Employees Salary in Each Department in Ascending 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 Ascending 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>> sortAscendingOrder=empList.stream().collect(Collectors.groupingBy(
Employee::getDeptName,Collectors.collectingAndThen(Collectors.toList(), list->list.stream().sorted(Comparator.comparingDouble(Employee::getSalary)))));
sortAscendingOrder.forEach((depName,streamOfEmployes)->{
System.out.println(depName);
System.out.println(streamOfEmployes.collect(Collectors.toList()));
}
);
}
}