
在 java 中,comparator 接口提供了一种比较两个对象以确定它们的顺序的方法。当您想要按自定义顺序对列表或数组等集合进行排序时,这特别有用。
当对象的自然排序(由其 comparable 实现定义)不能满足您的需求时,需要自定义 comparator。例如,按薪水、姓名或年龄对 employee 对象列表进行排序可能需要不同的比较器。
让我们逐步完成创建自定义比较器的过程。
考虑一个类 employee ,其中包含字段 name 、 age 和 salary。我们希望按 salary 升序对 employee 对象列表进行排序。
import java.util.comparator;
class employee {
private string name;
private int age;
private double salary;
// constructor, getters, and setters
public employee(string name, int age, double salary) {
this.name = name;
this.age = age;
this.salary = salary;
}
public double getsalary() {
return salary;
}
@override
public string tostring() {
return "employee{" + "name='" + name + ''' + ", age=" + age + ", salary=" + salary + '}';
}
}
class salarycomparator implements comparator<employee> {
@override
public int compare(employee e1, employee e2) {
return double.compare(e1.getsalary(), e2.getsalary());
}
}
在此示例中,salarycomparator 类实现 comparator 接口并重写比较方法以按员工的工资进行比较。
立即学习“Java免费学习笔记(深入)”;
现在,让我们创建一个员工列表,并使用我们的自定义比较器。
对其进行排序
import java.util.arraylist;
import java.util.collections;
import java.util.list;
public class main {
public static void main(string[] args) {
list<employee> employees = new arraylist<>();
employees.add(new employee("john", 28, 50000));
employees.add(new employee("anna", 32, 75000));
employees.add(new employee("mike", 25, 45000));
system.out.println("before sorting:");
employees.foreach(system.out::println);
// sort employees by salary
collections.sort(employees, new salarycomparator());
system.out.println("
after sorting by salary:");
employees.foreach(system.out::println);
}
}
运行上面的代码将产生以下输出:
before sorting:
employee{name='john', age=28, salary=50000.0}
employee{name='anna', age=32, salary=75000.0}
employee{name='mike', age=25, salary=45000.0}
after sorting by salary:
employee{name='mike', age=25, salary=45000.0}
employee{name='john', age=28, salary=50000.0}
employee{name='anna', age=32, salary=75000.0}
得益于自定义比较器,员工列表现在按工资升序排列。
有时,您可能需要更复杂的比较逻辑或希望按多个字段排序。
让我们修改比较器,首先按工资排序,然后在平局时按姓名排序。
class salarythennamecomparator implements comparator<employee> {
@override
public int compare(employee e1, employee e2) {
int salarycompare = double.compare(e1.getsalary(), e2.getsalary());
if (salarycompare == 0) {
return e1.getname().compareto(e2.getname());
}
return salarycompare;
}
}
使用 salarythennamecomparator ,您现在可以按工资和姓名对员工进行排序:
Collections.sort(employees, new SalaryThenNameComparator());
用 java 编写自定义比较器函数可以让您定制集合的排序行为以满足特定需求。无论您需要通过单个字段进行简单比较,还是需要通过多个条件进行复杂排序,comparator 都提供了灵活而强大的解决方案。
如果您有任何疑问或需要进一步说明,请随时在下面发表评论!
阅读更多帖子:如何用 java 编写自定义比较器函数?
以上就是如何用 Java 编写自定义比较器函数?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号