Comparator工具类对list对象多字段进行排序

题目

/*
第一行输入一个整数n,表示员工列表中员工的人数,接下来的n行,分别输入
员工的姓名、职级、工作年限、和工资信息,各项信息之间用空格分隔。

  • 某公司要针对员工情况统一调薪,现有一个员工列表,包含姓名、职级、工作年限、工资信息。现要求将该列表按以下规则重新排序:

1、职级高的排在前面

2、若职级相同,按工资少的排前面

3、若工资相同,工作年限长的排前面
输入:
6
张三 3 3 3000
李四 3 4 3000
王五 3 3 4000
赵六 4 3 3000
陆奇 4 4 4000
闫八 4 4 3980.99

输出:
赵六 4 3 3000
闫八 4 4 3980.99
陆奇 4 4 4000
李四 3 4 3000
张三 3 3 3000
王五 3 3 4000
**/

排序代码(Comparator工具类对list排序)

package test001;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Scanner;

public class PrintEmployee {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        List<Employee> employeeList = new ArrayList<>();
        int n = scanner.nextInt();
        for (int i = 0; i < n; i++) {
            Employee employee = new Employee();
            String next0 = scanner.next();
            employee.setName(next0);
            int next1 = scanner.nextInt();
            employee.setLevel(next1);
            int next2 = scanner.nextInt();
            employee.setWorkTime(next2);
            Double next3 = scanner.nextDouble();
            employee.setSalary(next3);
            employeeList.add(employee);
        }
        printEmployeeByOrder(employeeList);
    }

    private static void printEmployeeByOrder(List<Employee> employeeList) {
        Comparator<Employee> byLevel = Comparator.comparing(Employee::getLevel).reversed();
        Comparator<Employee> byWorkTime = Comparator.comparing(Employee::getWorkTime).reversed();
        Comparator<Employee> bySalary = Comparator.comparing(Employee::getSalary).reversed();
        employeeList.sort(byLevel.thenComparing(bySalary).thenComparing(byWorkTime));
        for (Employee employee : employeeList) {
            System.out.println(employee);
        }
    }
}

Employee员工实体类

package test001;

public class Employee {
    private String name;
    private Integer level;
    private Integer workTime;
    private Double salary;

    public Employee(String name, Integer level, Integer workTime, Double salary) {
        this.name = name;
        this.level = level;
        this.workTime = workTime;
        this.salary = salary;
    }

    public Employee() {
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getLevel() {
        return level;
    }

    public void setLevel(Integer level) {
        this.level = level;
    }

    public Integer getWorkTime() {
        return workTime;
    }

    public void setWorkTime(Integer workTime) {
        this.workTime = workTime;
    }

    public Double getSalary() {
        return salary;
    }

    public void setSalary(Double salary) {
        this.salary = salary;
    }

    @Override
    public String toString() {
        return name + " " + level + " " + workTime + " " + salary;
    }
}

排序结果

Comparator工具类对list对象多字段进行排序_第1张图片

你可能感兴趣的:(JAVA,list,java,数据结构)