java - 如果某些参数相等,如何对对象参数进行排序

标签 java sorting

我有一个 ArrayList,其中包含一些包含 3 个参数(id、name、salary)的对象。未排序列表:

public class Employee {
        private int id;
        private String name;
        private double salary;

        public Employee(int _id, String _name, double _salary) {
            this.id = _id;
            this.name = _name;
            this.salary = _salary;
        }

        public int getEmployeeID () {
            return this.id;
        }


        public String getEmployeeName () {
            return this.name;
        }

        public double getMonthSalary() {
            return this.salary;
        }

        public static void main(String[] argc) {
            ArrayList<Employee> list = new ArrayList<Employee>();
            list.add(new Employee(1, "asd", 1300));
            list.add(new Employee(7, "asds", 14025)); // this
            list.add(new Employee(2, "nikan", 1230));
            list.add(new Employee(3, "nikalo", 12330));
            list.add(new Employee(8, "aaaa", 14025)); // and this are equal
            list.add(new Employee(4, "nikaq", 140210));
            list.add(new Employee(5, "nikas", 124000)); 
            list.add(new Employee(6, "nikab", 14020));
        }
}

我想按薪水对列表进行排序,如果薪水相等,则按字母顺序对他们的名字进行排序。我尝试使用Collections.sort();,但它按所有参数排序。

例如:14025 和 14025 相等,因此按名称排序:asds, aaaa --> aaaa, asds

这是我尝试过的:

for (int i = 0; i < list.size() - 1; i++) {
    for (int j = 0; j < list.size() - 1; j++) {
        boolean isSorted = false;
        if (list.get(j + 1).getMonthSalary() > list.get(j).getMonthSalary()) {
            Employee temprary = list.get(j);
            list.set(j, list.get(j + 1));
            list.set(j + 1, temprary);
            isSorted = true;
        }

        if (isSorted) {
            if (list.get(j).getMonthSalary() == list.get(j + 1).getMonthSalary()) {
                Collections.sort(list, new Comparator < Employee > () {
                    @Override
                    public int compare(Employee s1, Employee s2) {
                        return s1.getEmployeeName().compareToIgnoreCase(s2.getEmployeeName());
                    }
                });
            }
        }
    }
}

最佳答案

Java有一个内置的机制来处理这样的问题 - Comparator s。你不应该重新发明轮子:

list.sort(Comparator.comparing(Employee::getMonthSalary)
                    .thenComparing(Employee::getEmployeeName));

关于java - 如果某些参数相等,如何对对象参数进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38032784/

相关文章:

C 如何将一个选项卡排序为多个选项卡

java - 使用新方法访问 ArrayList 时出现编译时错误

java - 如何在 Java 文档中查找 int[].length ?

java - 从自定义对话框获取多个结果——JavaFX

java - 如何将 JSP 中的选择值获取到 servlet? JAVAEE

python - 如何迭代编写归并排序?

algorithm - 快速排序的空间复杂度

java - 名称为 [DEFAULT] 的 FirebaseApp 不存在。 (对于 Spring 启动)

java - 在 Apache Spark (Java) 中按多个值对 JavaRDD 元组进行排序

python - 基于另一个相似矩阵对矩阵进行排序的Numpyic方法