简体   繁体   中英

Java8 Sorting Custom Objects having Custom Object in it

I have an Employee Object, with in it Department Object. I need to sort by Employee Object Fields and then by Department Fields too. Data looks like below.

public static List getEmployeeData() {

    Department account = new Department("Account", 75);
    Department hr = new Department("HR", 50);
    Department ops = new Department("OP", 25);
    Department tech = new Department("Tech", 150);

    List<Employee> employeeList = Arrays.asList(new Employee("David", 32, "Matara", account),
    new Employee("Brayan", 25, "Galle", hr), new Employee("JoAnne", 45, "Negombo", ops),
    new Employee("Jake", 65, "Galle", hr), new Employee("Brent", 55, "Matara", hr),
    new Employee("Allice", 23, "Matara", ops), new Employee("Austin", 30, "Negombo", tech),
    new Employee("Gerry", 29, "Matara", tech), new Employee("Scote", 20, "Negombo", ops),
    new Employee("Branden", 32, "Matara", account), new Employee("Iflias", 31, "Galle", hr));

    return employeeList;
    
}

I want to sort by Employee::name, Employee::Age, Department::DepartmentName how it can be sorted?

This should led to the desired result:

List<Employee> employees = getEmployeeData()
                .stream()
                .sorted(Comparator
                        .comparing(Employee::getName)
                        .thenComparing(Employee::getAge)
                        .thenComparing(e -> e.getDepartment().getName()))
                .collect(Collectors.toList());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM