一:首先定义Employee实体类
package com.yhd.comparator;
/**
* @author sunfei
* @CreateTime 2016-8-10 下午05:01:14
*/
public class Employee {
private Integer age;
private Integer salary;
private String name;
public Employee(Integer age, Integer salary, String name) {
super();
this.age = age;
this.salary = salary;
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Integer getSalary() {
return salary;
}
public void setSalary(Integer salary) {
this.salary = salary;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
二:实现比较器
package com.yhd.comparator;
import java.util.Comparator;
/**
* @author sunfei
* @CreateTime 2016-8-10 下午05:04:39
*/
public class EmployeeComparator implements Comparator<Employee> {
public int compare(Employee emp1, Employee emp2) {
//按照薪水降序排序,薪水高的排在前面,薪水低的排在后面。用后者减去前者;
int result = emp2.getSalary().compareTo(emp1.getSalary());
if(result != 0){
return result;
}
//薪水相同,按照年龄升序排序,年龄低的排在前面,年龄高的排在后面。用前者减去后者;
if(emp1.getAge() != null && emp2.getAge()!=null) {
result = emp1.getAge().compareTo(emp2.getAge());
}
if(result != 0){
return result;
}
//年龄相同,按照姓名排序。字母小的排在前面,字母大的排在后面。用前者减去后者;
if(emp1.getName()!=null && emp2.getName()!=null){
result = emp1.getName().compareTo(emp2.getName());
}
return result;
}
}
三:测试类
package com.yhd.comparator;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* @author sunfei
* @CreateTime 2016-8-10 下午05:09:38
*/
public class TestComparator {
/**
* @param args
*/
public static void main(String[] args) {
List<Employee> emps = new ArrayList<Employee>();
emps.add(new Employee(23, 4000, "c"));
emps.add(new Employee(12, 4000, "z"));
emps.add(new Employee(12, 2000, "a"));
Collections.sort(emps, new EmployeeComparator());
for(Employee employee : emps) {
System.out.println("年龄:"+employee.getAge()+"------"+"薪水:"+employee.getSalary()+"----"+"姓名:"+employee.getName());
}
}
}