java.util.Comparator使用示例

java.util.Comparator使用示例

Comparator的具体实现类
public   class  AgeComparator  implements  Comparator  {
  
public int compare(Object op1, Object op2) {
    Employee eOp1 
= (Employee) op1;
    Employee eOp2 
= (Employee) op2;

    
// 按年龄排序
    return eOp1.getAge()-(eOp2.getAge());
  }

}


public   class  NameComparator  implements  Comparator  {
  
public int compare(Object op1, Object op2) {
    Employee eOp1 
= (Employee) op1;
    Employee eOp2 
= (Employee) op2;

    
// 按姓名排序
    return eOp1.getName().compareTo(eOp2.getName());
  }

}


public   class  SalaryComparator  implements  Comparator  {
  
public int compare(Object op1, Object op2) {
    Employee eOp1 
= (Employee) op1;
    Employee eOp2 
= (Employee) op2;

    
// 按薪水排序
    return eOp1.getSalary()-(eOp2.getSalary());
  }

}


Employee类:

public   class  Employee {
  
protected String name;
  
protected int age;
  
protected int salary;
  
  
public Employee(String name,int age,int salary){
    
this.name=name;
    
this.age=age;
    
this.salary=salary;
  }

  
  
public int getAge() {
    
return age;
  }

  
public void setAge(int age) {
    
this.age = age;
  }

  
public String getName() {
    
return name;
  }

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

  
public int getSalary() {
    
return salary;
  }

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


测试:
public   class  Main {
  
public static void main(String[] args){
    List
<Employee> employees=new ArrayList<Employee>();
    
    employees.add(
new Employee("Andy",21,2000));
    employees.add(
new Employee("Felix",21,3000));
    employees.add(
new Employee("Bill",35,20000));
    employees.add(
new Employee("Helen",21,10000));
    employees.add(
new Employee("Cindy",28,8000));
    employees.add(
new Employee("Douglas",25,5000));
        
    
// 按名称排序
      Collections.sort(employees,new NameComparator());
      display(employees);

      
// 按年龄排序
      Collections.sort(employees,new AgeComparator());
      display(employees);
      
      
// 按薪水排序
      Collections.sort(employees,new SalaryComparator());
      display(employees);
  }

  
  
public static void display(List<Employee> employees){
    
for(Employee e:employees){
      System.out.println(
"雇员名="+e.getName()+" 年龄="+e.age+" 薪水="+e.getSalary());
    }

    
    System.out.println();
  }

}


输出:
雇员名 = Andy 年龄 = 21  薪水 = 2000
雇员名
= Bill 年龄 = 35  薪水 = 20000
雇员名
= Cindy 年龄 = 28  薪水 = 8000
雇员名
= Douglas 年龄 = 25  薪水 = 5000
雇员名
= Felix 年龄 = 21  薪水 = 3000
雇员名
= Helen 年龄 = 21  薪水 = 10000

雇员名
= Andy 年龄 = 21  薪水 = 2000
雇员名
= Felix 年龄 = 21  薪水 = 3000
雇员名
= Helen 年龄 = 21  薪水 = 10000
雇员名
= Douglas 年龄 = 25  薪水 = 5000
雇员名
= Cindy 年龄 = 28  薪水 = 8000
雇员名
= Bill 年龄 = 35  薪水 = 20000

雇员名
= Andy 年龄 = 21  薪水 = 2000
雇员名
= Felix 年龄 = 21  薪水 = 3000
雇员名
= Douglas 年龄 = 25  薪水 = 5000
雇员名
= Cindy 年龄 = 28  薪水 = 8000
雇员名
= Helen 年龄 = 21  薪水 = 10000
雇员名
= Bill 年龄 = 35  薪水 = 20000


你可能感兴趣的:(java.util.Comparator使用示例)